How to use groupby having with DB::raw in Laravel Query Builder?

How to use groupby having with DB::raw in Laravel Query Builder?

In this post we will give you information about How to use groupby having with DB::raw in Laravel Query Builder?. Hear we will give you detail about How to use groupby having with DB::raw in Laravel Query Builder?And how to use it also give you demo for it if it is necessary.

We most probably require to use group by having because if you work on small project then it’s not need to use generally. But if you work with big project like e-commerce, social or ERP level project then you may require to use having clause.

having clause, we can use simply if we have to compare with number or static value like as bellow:

->having("total_quantity","

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 column name.

In this example i want to show minimum quantity items, I have two tables one items 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 get that items using bellow query:

Example


$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","

->get();

print_r($items);

You will find bellow output get only items no. 2.

Array

(

[0] => stdClass Object

(

[id] => 2

[title] => Itsolutionstuff.com

[min_quantity] => 10

[total_quantity] => 5

)

)

Hope this code and post will helped you for implement How to use groupby having with DB::raw in Laravel Query Builder?. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

16  +    =  17

We accept paid advance and paid guest Posting on our Site : Contact US