laravel - 与多个中间表的多对多 Laravel Eloquent 关系
问题描述
我正在使用 Laravel 5.4 并具有如下模型和表结构:
users
-----
id
accounts
--------
id
holdings
--------
id
account_id (foreign key to account)
user_accounts
-------------
id
user_id
account_id
- 一个用户可以有多个账户
- 一个帐户可以由多个用户共享
- 每个账户有多个持仓
- 因此,用户通过他们的许多账户间接拥有许多资产。
我需要帮助在 User 模型上定义一个名为“holdings”的关系,以获取适用于用户的所有馆藏(基于他们链接到的帐户)。
我尝试了很多不同的东西,并且在谷歌上花了很长时间。我可以同时使用 belongsToMany 和 hasManyThrough,但它们似乎只适用于 3 个表关系,其中中间表存储来自其他表的主键。如果我使用holdings 表上的account_id 外键来消除通过accounts 表加入的需要,我可以将我的关系减少到3 个表(而不是4 个),但是我似乎无法让它工作。
属于ToMany - holdings
。id
需要holdings
。account_id
:
select * from `holdings`
inner join `user_accounts` on `holdings`.`id` = `user_accounts`.`account_id`
where `user_accounts`.`user_id` = ?
hasManyThrough - user_accounts
。id
需要user_accounts
。account_id
:
select * from `holdings`
inner join `user_accounts` on `user_accounts`.`id` = `holdings`.`account_id`
where `user_accounts`.`user_id` = ?"
解决方案
好吧,严格来说,这不是我询问 laravel 5.4 的答案,但它是一个可能的解决方案。
事实证明我很幸运,因为我遇到了在两个表上定义本地键的 Laravel 的 belongsToMany 关系,这表明 Laravel 5.5 中增强了 belongsToMany 关系以支持这种类型的场景。
我已将我的项目升级到 L5.5,并用关系替换了我的 hack:
return $this->belongsToMany(Holding::class, 'user_accounts', 'user_id', 'account_id', null, 'account_id');
并且很高兴地说它似乎工作得很好 - 至少对于我的用例的基本获取,我没有尝试任何更新等。
感谢@cyberfly 和那些在上面发布答案的人
推荐阅读
- javascript - 是什么让 JavaScript 函数异步?
- sql - 接受 item_num 并报告其描述、价格和现有数量的 PL/SQL 过程不起作用
- python - 如何在 Python 中隐藏一个值?(显示为 *)
- python - 分析 pandas 中的数据,其中一些值是 dicts 列表
- c# - 更改输入时软键盘消失
- mysql - 使用 TinyMCE 发布的图像是否有大小限制?
- php - 在该选项卡中单击分页链接时如何激活选项卡?
- haskell - 我可以在 Data.Aeson 和 Data.Yaml 之间重用 ToJSON 和 FromJSON 实例吗?
- javascript - 检查总值的功能
- android - 导致崩溃的android按钮