简体   繁体   中英

How to join sub-query in laravel elequent

How do this query in laravel query builder?

select * from products p join 

(
select product_id,sum(qty) total_sales 

from orders where qty !=0 group by product_id
) 

s on p.id = s.product_id

order by s.total_sales desc

There are different ways are there to do the same thing. But you can do with Raw Expressions is very similar to your above code.

if you want to use Eloquent, Do this provided the orders table has product_id that is a foreign key from products

DB::table('products')->join('orders','products.id','orders.product_id')->where('orders.qty','!=',0)->get()

The first part for sub-query for join ed part. It is joined with toSql() method inside the raw statement.

$subQuery = DB::table('orders')
    ->where('qty', '!=', DB::raw(0))
    ->groupBy('product_id')
    ->select('product_id', DB::raw('sum(qty) as total_sales'));

return DB::table('products as p')
    ->join(DB::raw('(' . $subQuery->toSql() . ') s'), 'p.id', '=', 's.product_id')
    ->orderByDesc('s.total_sales')
    ->get();

It prints the following sql;

SELECT *
FROM `products` AS `p`
         INNER JOIN (
    SELECT `product_id`, SUM(qty) AS total_sales
    FROM `orders`
    WHERE `qty` != 0
    GROUP BY `product_id`
) s ON `p`.`id` = `s`.`product_id`
ORDER BY `s`.`total_sales` DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM