Laravel 从子查询中查询生成器 Select

Laravel query Builder Select from subquery

我正在尝试将 sql 查询转换为 Laravel 查询生成器, 但我很难理解哪种是 Laravel 中 FORM SUBQUERY 的最佳方式, 因为如果我没记错的话,这不是您通常可以使用查询生成器执行的操作,但您应该以原始方式实现。

这样对吗?

这个应该怎么翻译?

 SELECT t1.* FROM (//with out sub query it would be just products AS t1
                   SELECT SUM(amount)AS amount, products.* 
                   FROM products ,orders 
                   WHERE orders.product_id = products.product_id 
                   GROUP BY orders.product_id )AS t1
 LEFT OUTER JOIN products as t2 
 ON(t1.name = t2.name AND t1.year_production< t2.year_production) 
 WHERE t2.name is null 

我可以在不添加子查询的情况下进行翻译

 $poductlist =Product::from('products AS t1')->select('t1.*')
                     ->leftjoin('products AS t2', function($join){
                               $join->on('t1.name','=', 't2.name')
                                    ->on('t1.year_production','<','t2.year_production')
                                    ->whereNull('t2.name')
                                    ->orderBy('t2.name','desc');})
                     ->get();

我相信您可以将查询重写为相关子查询,以过滤名称重复的最大值 year_production 的产品

select p.product_id,
       p.name,
       coalesce(sum(o.amount),0) as amount
from products as p
left join orders o on p.product_id = o.product_id
where exists (
    select 1
    from products p1
    where p1.name = p.name
    having max(p1.year_production) = p.year_production
)
group by p.product_id, p.name
order by p.product_id

在查询生成器中,您可以将其转换为

$products = DB::table('products as p')
               ->select(['p.product_id',
                         'p.name',
                          DB::raw('coalesce(sum(o.amount),0) as amount')
                        ])
               ->leftJoin('orders as o', 'p.product_id', '=', 'o.product_id' )
               ->whereExists(function ($query) {
                   $query->select(DB::raw(1))
                         ->from('products as p1')
                         ->whereRaw(DB::raw('p1.name = p.name'))
                         ->havingRaw('max(p1.year_production) = p.year_production')
                         ;
              })
              ->groupBy('p.product_id','p.name')
              ->orderBy('p.product_id')
              ->get();