Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query builder GROUP BY, HAVING, COUNT in Laravel

how to express this code in query builder. I'm using Laravel 6.

SELECT * FROM feedback GROUP BY noTicket having count(`status`) < 2 

My Code:

$feedback = DB::table('feedback')
            ->groupBy('noTicket')
            ->having('count(status)', '<', 2)
            ->get();

Error Code:

SQLSTATE[42000]: Syntax error or access violation: 1055 'sifora.feedback.idFeedback' isn't in GROUP BY 
(SQL: select * from `feedback` group by `noTicket` having `count(status)` < 2) 

What is wrong with my code? It seems match between sql code vs query builder.

Thank you

like image 544
Ikra Avatar asked Dec 22 '22 17:12

Ikra


1 Answers

This is the working version of query

select noTicket
from feedback
group by noTicket
having count(status) < 2;

This is the query builder;

return DB::table('feedback')
    ->groupBy('noTicket')
    ->having(DB::raw('count(status)'), '<', 2)
    ->pluck('noTicket'); // you may replace this with get()/select()
like image 134
Ersoy Avatar answered Dec 25 '22 07:12

Ersoy