简体   繁体   English

如何在 laravel elequent 中加入子查询

[英]How to join sub-query in laravel elequent

How do this query in laravel query builder?如何在 laravel 查询生成器中进行此查询?

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.但是你可以用Raw Expressions做的和你上面的代码很相似。

if you want to use Eloquent, Do this provided the orders table has product_id that is a foreign key from products如果您想使用 Eloquent,请执行此操作,前提是订单表的 product_id 是产品的外键

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.第一部分用于join部分的子查询。 It is joined with toSql() method inside the raw statement.它与raw语句中的toSql()方法连接。

$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;它打印以下 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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