laravel - laravel 雄辩 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 会在 Companies 列中查找 user_id 列,而不是在 users 表中查找 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();
推荐阅读
- javascript - 当它用作结果框时,有没有办法限制输入中的十进制字符数?
- visual-studio-code - 修复文本背景颜色的用户设置
- java - Java Selenium - POM - html xpath - 没有这样的元素:无法找到元素
- assembly - 汇编 - 为什么这些代码块输出不同?
- phpmyadmin - 单击浏览表时phpMyAdmin会自动运行奇怪的查询
- kubernetes - 我可以在我的 kubernetes 部署中使用多个 PodAffiniy 吗?
- security - 导致 ssh 客户端要求密码的原因是可能的身份验证,但在拒绝登录之前没有提示用户输入密码?
- javascript - 如何在节点 js 的模板文字中调用函数
- javascript - 如何更改气泡图中某个元素的位置
- mysql - mySQL 中各组之间总数的百分比