我有两个模型“国家”和“州”。 它们之间的关系如下: 国家:
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不存在,因为它被命名为country_id 因为国家/地区表的名称是国家/地区。
请帮忙解决这个错误。
最佳答案
您的外键
不匹配,请将外键列添加为关系
函数上的第二个
参数。
public function States()
{
return $this->hasMany('App\State','countries_id');
}
按照约定
,Eloquent 采用所属模型的“蛇形”
名称,并使用 _id
为其添加后缀
> 作为外键
。这就是为什么它获取的是 country_id
而不是 countries_id
。
关于php - 在 Laravel 中获取具有 Eloquent 关系的错误列的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48396374/