"Laravel Eloquent DB::Raw query does not support using WHERE statement and subquery at the same time"
P粉191610580
P粉191610580 2024-01-16 13:01:17
0
1
455

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粉191610580
P粉191610580

reply all(1)
P粉517814372

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();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!