search

Home  >  Q&A  >  body text

"Laravel Eloquent DB::Raw query does not support using WHERE statement and subquery at the same time"

When I paste the following query into my SQL tool, it runs fine, but returns zero rows when run through 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
";

Due to the complexity of the actual query, I couldn't completely convert it into an Eloquent query, so I used DB::select(DB::raw($searchQuery)); to execute it.

If I remove where main_query.cl_count > 1, the query works fine. What causes it to fail, and how can I rewrite the code?

P粉191610580P粉191610580321 days ago507

reply all(1)I'll reply

  • P粉517814372

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

    Try the following code, generated by 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();

    reply
    0
  • Cancelreply