Laravel Join with Subquery in Query Builder Example
In this post i want to show you how to use subquery with join in laravel query builder. Whenever you need to use subquery in your laravel project you can use following example and learn hot to use subquery. In bellow example you can see we add subquery using DB::raw(), DB::raw() throught we can select our subtable and after in second argument i added compare your field. That way you can easily fire subquery with laravel 5.2 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);
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Add Custom Attribute in Laravel Model?
- Laravel Get Min Value of Column Example
- Laravel - How to Upload Picture in Registration Form?
- Laravel Profile Image Upload Tutorial with Example
- How to Add Extra Field in Registration Form in Laravel?
- Laravel Eloquent Find by Column Name Example
- Laravel - How to use Subquery in Select Statement?
- How to Get Last 2 Days Records from Table using MySQL Query?
- Laravel Group By with Month and Year Example
- Laravel Select with Sum Query Example
- How to Get Query Log in Laravel Eloquent?