【问题标题】:How to get all records using Eloquent that aren't associated with a model?如何使用 Eloquent 获取与模型无关的所有记录?
【发布时间】: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


【解决方案1】:

Country 上的 group 关系也需要是 belongsToMany。如果一侧是belongsToMany,另一侧也必须是。 belongsTo 表示外键在该模型上,但情况并非如此,因为存在数据透视表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2015-09-01
    • 2013-12-22
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多