如何用雄辩的方式在FROM中编写子查询?

时间:2018-06-23 15:51:18

标签: laravel eloquent

我想将子查询合并到主查询中

这是我的原始查询

select field1, field3, total
from (select field1, field3, sum(field2) as total
      from sales
      group by field1, field2
      having total <> 0
     ) s
group by field1;

我尝试将其合并

$sub = Sales::select(DB::raw('field1,field3,SUM(field2)as total'))         
            ->groupBy('field1',DB::raw('field3 having total<> 0'));  

 $main = DB::table(DB::raw("({$sub->toSql()}) as sub") )
            ->select('field1', 'field3','total');
            $main ->mergeBindings($sub->getQuery());
            $main ->groupBy('field1');       
            $main ->get();

但是它不返回任何数据。这怎么了

2 个答案:

答案 0 :(得分:0)

我建议使用fromRaw方法:

$finalQuery = self::newQuery()->fromRaw("({$subQuery->toSql()}) as sub")

答案 1 :(得分:0)

如果@DigitalDrifter响应中提到的fromSub方法未使用Laravel 5.6,则只需在pizzas_offered函数中包含子查询即可

from()