【问题标题】:Fetching data with wrong column with eloquent relationship in laravel在laravel中以雄辩的关系获取错误列的数据
【发布时间】:2018-07-01 22:58:35
【问题描述】:

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

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 子句'中的未知列'states.country_id'(SQL:select * from states where states.country_id = 11 和 states.country_id 是不为空)

country_id 不存在是对的,因为它被命名为 countries_id 因为 Country 的表名称是国家。

请帮忙解决这个错误。

【问题讨论】:

  • states.country_id 引用表 states 和列 country_id,如果你想引用 Country 表使用 country。

标签: php laravel eloquent has-many


【解决方案1】:

在关系定义中添加外键:

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

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

【讨论】:

    【解决方案2】:

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

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

    通过convention,Eloquent 将拥有模型的"snake case" 名称和suffix_id 作为foreign key。这就是为什么它得到country_id 而不是countries_id

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 2014-03-26
      • 2016-07-22
      • 2018-06-14
      • 2020-12-02
      • 2019-07-16
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多