Laravel Eloquent Query | How to use groupby having with DB::raw in Laravel Query Builder?
We most probably require to use group by having because if you work on a small project then it does not need to use generally. But if you work with big projects like e-commerce, social, or ERP level projects then you may require to use the having clause.
you can also use groupby having with DB raw in the laravel app.
having clause, we can use simply if we have to compare with a number or static value like as below:
->having("total_quantity","<",10)
But we need to compare with 10 instead of column name then it can’t directly use column name. At that time we should use DB::raw() with the column name.
In this example I want to show minimum quantity items, I have two tables one item and another one items_count both MySQL table layout is here
items table
items_count table:
I need to get that product has less quantity to min_quantity of items table, so we check to get that item using below query
$items = DB::table("items")->select("items.id","items.title","items.min_quantity",DB::raw('SUM(items_count.quantity) as total_quantity'))->join("items_count","items_count.id_item","=","items.id")->groupBy("items.id")->having("total_quantity","<",DB::raw("items.min_quantity"))->get();print_r($items);
output
Array([0] => stdClass Object([id] => 2[title] => Itsolutionstuff.com[min_quantity] => 10[total_quantity] => 5))