我该如何使用 eloquent 在 Laravel 4.2 中编写这个 SQL 查询?
SELECT *
FROM participants
WHERE user_id IN (1, 2)
GROUP BY convo_id
HAVING count(DISTINCT user_id) = 2
AND count(DISTINCT convo_id) = 1
我已经尝试过了
Participant::whereIn('user_id', $participantIds)
->groupBy('convo_id')
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->whereRaw('count(DISTINCT convo_id) = 1')
->get();
但我收到此错误
SQLSTATE[HY000]: General error: 1111 Invalid use of group function (SQL: select * from `participants` where `user_id` in (1, 2, 4) and count(DISTINCT convo_id) = 1 group by `convo_id` having count(DISTINCT user_id) = 3)
最佳答案
我的错误。 whereRaw 也应该具有 Raw。
Participant::whereIn('user_id', $participantIds)
->groupBy('convo_id')
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->havingRaw('count(DISTINCT convo_id) = 1')
->get();
关于php - 在 eloquent 中构建 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39240420/