Showing posts with label Select SubQuery. Show all posts
Showing posts with label Select SubQuery. Show all posts

Sunday, June 25, 2017

Laravel 5: How to Select from Sub-query using Laravel Query Builder

Laravel 5: How to Select from Sub-query using Laravel Query Builder. It's very easy to use Sub-Query as Select query in Laravel. Below is a sample code snippet:



$query = DB::table("employee")->whereIn("id", array(1, 2, 3, 4));
$result = DB::table(DB::raw("(" . $query->toSql() . ") as res"))
    ->mergeBindings($query)
    ->whereIn("res.id", array(2, 3))->get();

Which will generate below SQL:

select * from (select * from `employee` where `id` in (1, 2, 3, 4)) as res 
where `res`.`id` in (2, 3))