HDTuto.com

PHP Laravel select with join subquery example


Hi PHP Laravel Developer,

Today, i will let you know how to use select with join subquery using Laravel eloquent. You will learn inner join or left join with select query in Laravel eloquent. Let's see example for laravel 5, laravel 5.1, laravel 5.2, laravel 5.3, laravel 5.4, laravel 5.5 eloquent select join query example.

Here we will use DB::raw() with join() function of laravel 5 eloquent. In this article i will let you know how you can convert mysql or sql query of select with join in Laravel 5 application.

As you can see bellow i added simple Mysql Query for select with join in Laravel. So let's see bellow query:

MySQL Query:

SELECT

products.*, product_stock.quantity_group

FROM

products

INNER JOIN (SELECT

product_stock.id_product,

GROUP_CONCAT(product_stock.quantity) as quantity_group

FROM product_stock

GROUP BY product_stock.id_product) AS product_stock

ON product_stock.id_product = products.id

GROUP BY products.id

As you can see above sql query now we convert into laravel 5 db query.

DB Query:

$data = DB::table("products")

->select("products.*","product_stock.quantity_group")

->join(DB::raw("(SELECT

product_stock.id_product,

GROUP_CONCAT(product_stock.quantity) as quantity_group

FROM product_stock

GROUP BY product_stock.id_product

) as product_stock"),function($join){

$join->on("product_stock.id_product","=","products.id");

})

->groupBy("products.id")

->get();


print_r($data);

I hope you found your best..... :)






January 4, 2018 | Category : PHP Laravel
Related Posts