Home Laravel Laravel Join with Subquery in Query Builder Example

Laravel Join with Subquery in Query Builder Example

by Shahriar Sagor

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.

close

You may also like