Thursday 10 March 2016

Writing the Subquery in Laravel 5.2

Please follow the example below to write the the Sub Query on Laravel 5.2:
// NOTE: Please do not forgot add below line at the top to use DB instance
USE DB;
$result = static::select('id')
->where( 'id', '!=', $currentLevelId)
->where('level', '>', DB::raw("(SELECT level FROM " . $this->table . " WHERE id='".$currentLevelId."')") )
->orderBy('level')->first();

Will produce the below subquery:
SELECT * FROM `approval_levels` WHERE `id` != 2 AND `level` > (SELECT LEVEL
FROM approval_levels WHERE id='2') ORDER BY `level` ASC LIMIT 1
Another Example:
$data = DB::table("items")
 ->select("items.*","items_count.price_group","items_count.quantity")
 ->join(DB::raw("(SELECT 
   items_count.id,
   GROUP_CONCAT(items_count.price) as price_group,
   FROM items_count
   GROUP BY items_count.id
   ) as items_count"),function($join){
  $join->on("items_count.id","=","items.id");
 })
 ->groupBy("items.id")
 ->get();

Hope it helps!

1 comment:

Please post any queries and comments here.