如何解决laravel eloquent hasOneThrough 外键
我有以下结构:
**users**
id,company_id
**companies**
id,country_id
**countries**
id,name
现在我想让用户拥有这样的公司和国家:
User::with('country')->get();
public function country() {
return $this->hasOneThrough(Country::class,Company::class);
}
然而,Eloquent 正在寻找公司列中的 user_id 列,而不是用户表中的 company_id 列:
select `countries`.*,`companies`.`user_id` as `laravel_through_key`
from `countries`
inner join `companies` on `companies`.`id` = `countries`.`company_id`
解决方法
如文档中所述
return $this->hasOneThrough(
Country::class,Company::class,'id',// Foreign key on the Companies table...
'id',// Foreign key on the Country table...
'company_id',// Local key on the users table...
'country_id' // Local key on the Companies table...
);
一种更简单的解决方案是使用现有关系 belongsTo
User::with('company.country')->get();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。