Laravel Join with Subquery in Query Builder Example

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i want to show you how to use subquery with join in laravel query builder. When we need to use a subquery in our laravel project we can use the following example and we can learn hot to use subquery. Now in bellow example we can see we add subquery by using DB::raw(), DB::raw() through we can select our subtable and then after in second argument i can added compare our field. On that way we can easily fire subquery with laravel query builder.

Example:
$data = DB::table("items")
  ->select("items.*","items_count.price_group","items_count.quantity_group")
  ->join(DB::raw("(SELECT 
      items_count.id_item,
      GROUP_CONCAT(items_count.price) as price_group,
      GROUP_CONCAT(items_count.quantity) as quantity_group
      FROM items_count
      GROUP BY items_count.id_item
      ) as items_count"),function($join){
        $join->on("items_count.id_item","=","items.id");
  })
  ->groupBy("items.id")
  ->get();
print_r($data);

Read Also : Laravel and AngularJS CRUD with Search & Pagination Example

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →