在 laravel 中获取具有 eloquent 关系的错误列的数据

Fetching data with wrong column with eloquent relationship in laravel

我有两个模型国家和州。 它们之间的关系如下: 国家:

public function States()
{
   return $this->hasMany('App\State');
}

州:

public function Country()
{
  return $this->belongsTo('App\Country');
}

现在,我想在 show 方法中获取属于该国家/地区的状态。

public function show(Country $country)
{
    $states = $country->States()->get();
    dd($states);
}

但是,这里会抛出一个错误: SQLSTATE[42S22]:未找到列:1054 'where clause' 中的未知列 'states.country_id'(SQL:select * 来自 states,其中 states.country_id = 11 并且 states.country_id 不为空)

country_id不存在是对的,因为它被命名为countries_id 因为 table 的国家名称是 countries.

请帮忙解决这个错误。

将外键添加到关系定义中:

return $this->hasMany('App\State', 'countries_id');

https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

您的 foreign key 不匹配,请在您的 relationship 函数中添加外键列作为 second 参数。

public function States()
{
  return $this->hasMany('App\State','countries_id');
}

通过convention,Eloquent取所属模型的"snake case"名称suffix_idforeign key。这就是为什么它得到 country_id 而不是 countries_id.