在我的 laravel 项目中,我有如下所示的表格。
groups
和users
是多对多的关系,即一个用户可以属于多个组。
group_user
表是表示哪个用户属于哪个组的中间表。
slot_votes
表记录用户对插槽的投票。它与groups
表的关系是groups
表hasMany slot_votes
。
组
表
|id | channel_id |
+---+---------+
|1 | U124 |
|2 | U123 |
|3 | U125 |
|4 | U127 |
用户
表
|id | name |
+---+---------+
|1 | A |
|2 | B |
|3 | C |
|4 | D |
group_user
表
|id | group_id | user_id |
+---+----------+-----------+
|1 | 1 | 1 |
|2 | 2 | 1 |
|3 | 2 | 2 |
|4 | 3 | 3 |
|5 | 4 | 3 |
|6 | 1 | 4 |
slot_vote
表
|id | user_id | group_id | slot |
+---+---------+-----------+-----------+
|1 | 1 | 1 | A |
|2 | 2 | 1 | B |
|3 | 2 | 2 | C |
|1 | 1 | 4 | C |
我的问题是如何使用 Laravel Eloquent 获取所有成员投票的组 ID?
例如,如果组 1 的成员是 $userId = [1, 4]
并且用户 1 和 4 都已投票(因此存在于 slot_votes 表中),我想获得组 1 id在结果中。
我尝试过的:
Group::whereHas('users', function ($query, $votedUser) {
$query->whereIn(
'id',
SlotVote::where('group_id', $groupId)->pluck('user_id')->unique()
);
}, '=', count($votedUser))->get();
但我不知道如何在 whereIn
子句中获取 $groupId
。另外,我担心查询性能。关于如何获得所需结果的任何想法?
先谢谢你。
最佳答案
我设法使用以下代码解决了这个问题:
Group::leftJoin('group_user', 'groups.id', '=', 'group_user.group_id')
->leftJoin('slot_votes', 'group_user.user_id', '=', 'slot_votes.user_id')
->selectRaw(
"groups.id, channel_id,
count(distinct group_user.user_id) as members,
count(distinct slot_votes.user_id) as voted_members",
)
->groupBy('groups.id')
->havingRaw('members=voted_members')
->get();
关于php - 在另一个表 Laravel 中查找数据透视表中所有 ID 的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69671407/