搜索

首页  >  问答  >  正文

"Laravel Eloquent DB::Raw查询不支持同时使用WHERE语句和子查询"

当我将以下查询粘贴到我的SQL工具中时,它可以正常运行,但是通过Laravel运行时返回零行。

$sql = "
SELECT main_query.* FROM (
    SELECT
        c.id,
        c.name,
        c.order,
        cd.case,
        (SELECT count(*) from logs cl
            where
            c.id = cl.id
            and cl.status = 'OPEN'
        ) as cl_count,
        sdsc.task
    FROM `table` c
    INNER JOIN `table2` cd ON (c.id = cd.id)
    LEFT JOIN `table3` sdsc ON (c.id = sdsc.id)
    WHERE
        c.status = 'NEW'
    GROUP BY c.id
    ORDER BY cd.updated_at DESC                    
) main_query                
where main_query.cl_count > 1
GROUP BY main_query.id
ORDER BY main_query.updated_at DESC
limit 0,20
";

由于实际查询的复杂性,我无法完全将其转换为Eloquent查询,因此我使用DB::select(DB::raw($searchQuery)); 来执行它。

如果我删除where main_query.cl_count > 1,查询就可以正常运行。是什么导致它失败,并且我该如何重写代码?

P粉191610580P粉191610580319 天前506

全部回复(1)我来回复

  • P粉517814372

    P粉5178143722024-01-17 11:29:37

    尝试以下代码,由https://sql2builder.github.io/生成

    DB::query()->fromSub(function ($query) {
        $query->from('table')
            ->select('table.id', 'table.name', 'table.order', 'table2.case', 'table3.task')
            ->on(function ($query) {
                $query->where('table.id','=','table2.id');
            })
            ->on(function ($query) {
                $query->where('table.id','=','table3.id');
            })
            ->where('table.status','=','NEW')
            ->groupBy('table.id')
            ->orderBy('','desc');
    },'main_query')
    ->select('main_query.*')
    ->where('main_query.cl_count','>',1)
    ->groupBy('main_query.id')
    ->orderBy('','desc')
    ->get();

    回复
    0
  • 取消回复