【问题标题】:Building SQL query in eloquent用 eloquent 构建 SQL 查询
【发布时间】:2017-01-07 12:02:30
【问题描述】:

我将如何使用 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)

【问题讨论】:

    标签: php mysql sql laravel eloquent


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

      最后尝试 groupBy

      Participant::whereIn('user_id', $participantIds)                        
                          ->havingRaw('count(DISTINCT user_id) = '. sizeof($participantIds))
                          ->whereRaw('count(DISTINCT convo_id) = 1')
                          ->groupBy('convo_id')
                          ->get();
      

      【讨论】:

        猜你喜欢
        • 2018-10-27
        • 2021-10-02
        • 1970-01-01
        • 2020-03-19
        • 2018-07-28
        • 2021-08-17
        • 1970-01-01
        • 1970-01-01
        • 2016-03-30
        相关资源
        最近更新 更多