【发布时间】:2021-01-15 18:14:44
【问题描述】:
我是使用 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`))
【问题讨论】:
-
我认为您错过了国家/地区表架构中的外国 ID:
$table->foreignId('group_id'); -
我有一个数据透视表(country_group)。我觉得够了……
-
您已建立多对多关系。您应该在两个模型中创建一个函数并将其用于查询
标签: laravel eloquent laravel-8