Laravel查询联接和计数

时间:2020-09-10 15:13:06

标签: php laravel

我正在尝试将以下SQL查询复制到laravel控制器中,但没有运气。该查询可以作为直接mysql查询正常工作,因此数据存在问题,但是使用laravel查询构建器使我感到困惑。我试图在控制器中使用'Raw()'函数和变量,但这仍然不能从查询中返回数据。任何帮助都将不胜感激。

SELECT * 
 FROM (SELECT * from figures 
) t2
  left join 
( SELECT
    figure_id, 
    SUM(IF(trade='1', trade, 0)) as trades,
    SUM(IF(sale='1', sale, 0)) as sales
FROM userfigures
GROUP BY figure_id ) t1
ON (t1.figure_id = t2.id)

原始命令

    $sql = "SELECT * FROM (SELECT * from figures) t2 left join ( SELECT figure_id, SUM(IF(trade='1', trade, 0)) as trades, SUM(IF(sale='1', sale, 0)) as sales FROM userfigures GROUP BY figure_id ) t1 ON (t1.figure_id = t2.id)";
   $sellers = userfigures::Raw($sql)->get();

2 个答案:

答案 0 :(得分:1)

使用DB::select代替userfigures::Raw https://laravel.com/docs/7.x/database#running-queries

答案 1 :(得分:1)

尝试:

DB::table('figures as t1')
  ->leftJoin(DB::table('userfigures as t2')
  ->select('figure_id',
           DB::raw("SUM(IF(trade = '1', trade, 0)) AS trades"), 
           DB::raw("SUM(IF(sale = '1', sale, 0)) AS sales")
  )
  ->groupBy('figure_id'), 't1.figure_id', 't2.id')
  ->get();