如何使用 Eloquent 获取与模型无关的所有记录?

How to get all records using Eloquent that aren't associated with a model?

我是使用 Laravel 框架的新手,我想获取所有不属于某个组的国家/地区。

数据库结构:

Schema::create('countries', function (Blueprint $table) {
    $table->id();
    $table->string('code')->index();
    $table->string('name');
    $table->timestamps();
    $table->softDeletes();
});

Schema::create('groups', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->foreignId('currency_id')->constrained('currencies')->onDelete('CASCADE')->cascadeOnUpdate();
    $table->timestamps();
});

Schema::create('country_group', function (Blueprint $table) {
    $table->foreignId('group_id')->constrained('groups')->onDelete('CASCADE')->cascadeOnUpdate();
    $table->foreignId('country_id')->constrained('countries')->onDelete('CASCADE')->cascadeOnUpdate();
});

Schema::create('currencies', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name', 50)->unique();
    $table->string('code', 50)->unique();
    $table->string('symbol', 5)->nullable();
    $table->timestamps();
});

群模型:

class Group extends Model
{
    protected $table = 'groups';
    protected $fillable = ['name','currency_id'];

    public function countries()
    {
        return $this->belongsToMany(Country::class);
    }

    public function currency()
    {
        return $this->belongsTo(Currency::class);
    }
}

国家型号:

class Country extends Model
{
    protected $table = 'countries';
    protected $fillable = ['code','name'];

    public function provinces()
    {
        return $this->hasMany(CountryProvince::class);
    }
    
    public function group()
    {
        return $this->belongsTo(Group::class);
    }
}

我正在尝试获取与组无关的所有国家/地区:

Country::doesntHave('group')->get()

但得到预期:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'countries.group_id' in 'where clause' (SQL: select * from `countries` where not exists (select * from `groups` where `countries`.`group_id` = `groups`.`id`))

Country 上的 group 关系也需要是 belongsToMany。如果一侧是 belongsToMany 另一侧也必须是。 belongsTo 表示外键在该模型上,但事实并非如此,因为有一个枢轴 table.