首页 > 解决方案 > 与多个中间表的多对多 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 - holdingsid需要holdingsaccount_id

select * from `holdings`
inner join `user_accounts` on `holdings`.`id` = `user_accounts`.`account_id`
where `user_accounts`.`user_id` = ?

hasManyThrough - user_accountsid需要user_accountsaccount_id

select * from `holdings`
inner join `user_accounts` on `user_accounts`.`id` = `holdings`.`account_id`
where `user_accounts`.`user_id` = ?"

标签: laravellaravel-5eloquent

解决方案


好吧,严格来说,这不是我询问 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 和那些在上面发布答案的人


推荐阅读