Laravel 5 Query Builder左连接

时间:2018-03-18 21:20:27

标签: laravel-5 laravel-query-builder

我想在laravel中执行以下mysql命令

SELECT stars.*, SUM(points.amount) AS total_points
FROM stars
LEFT JOIN points ON stars.id = points.star_id 
GROUP BY stars.id

所以我写道:

\DB::table('stars')
            ->leftJoin('points', 'stars.id', '=', 'points.star_id')
            ->select(\DB::raw("stars.*, SUM('points.amount') AS total_points"))
            ->groupBY('stars.id')
            ->get();

当我转储并死掉结果时,我看到total_points为0.0。什么错了?

1 个答案:

答案 0 :(得分:2)

也许是引号中的问题?

->select(\DB::raw("stars.*, SUM('points.amount') AS total_points"))

正确:

->select(\DB::raw("stars.*, SUM(points.amount) AS total_points"))

简单变体:

->selectRaw('stars.*, SUM(points.amount) AS total_points')