我将如何使用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)
答案 0 :(得分:1)
我的错误。 whereRaw也应该有Raw。
Participant::whereIn('user_id', $participantIds)
->groupBy('convo_id')
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->havingRaw('count(DISTINCT convo_id) = 1')
->get();
答案 1 :(得分:0)
最后尝试groupBy
Participant::whereIn('user_id', $participantIds)
->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
->whereRaw('count(DISTINCT convo_id) = 1')
->groupBy('convo_id')
->get();