我有多个表的som结果,由
选择$places = Place::with(['rates' => function($query)
{
$query->select('id', 'place_id', 'criterion_id', 'value');
}])->select('id', 'coords')->get();
我需要按值的总和(或平均值)对这个结果进行排序。我怎样才能做到这一点?我试着用
$query->select('id', 'place_id', 'criterion_id', 'value')->sum('value');
但它不起作用。
最佳答案
如果它对你有用。您可以使用 JOIN
而不是 Eager Loading。
代码如下:
Place::leftJoin('rates', 'places.id', '=', 'rates.place_id')
->selectRaw('places.*, SUM(rates.value) as sumOfRateValues')
->groupBy('places.id')
->orderBy('sumOfRateValues', 'DESC')
->get();
关于mysql - 使用查询构建器(laravel)按 desc 求和和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503716/