【发布时间】:2018-10-05 11:41:44
【问题描述】:
我使用的是 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 个),但是我似乎无法让它工作。
belongsToMany - 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 laravel-5 eloquent