使用eloquent更新选择计数

时间:2016-10-19 14:55:55

标签: laravel eloquent laravel-5.2

我有一个雄辩的查询,它返回表中最常找到的10个名字。

$topPeople = $model
    ->select(['name', DB::raw('COUNT(*) as count')])
    ->groupBy('name')
    ->orderBy('count', 'desc')
    ->take(10)
    ->get();

这适用于返回结果,但我想更新这些记录而不是返回数据。当我使用update而不是get;

$model
    ->select(['name', DB::raw('COUNT(*) as count')])
    ->groupBy('name')
    ->orderBy('count', 'desc')
    ->take(10)
    ->update(['popular' => 1]);

我收到了错误;

  

SQLSTATE [42S22]:未找到列:1054'order clause'中的未知列'count'

更新这些记录中popular字段的有效方法是什么?

1 个答案:

答案 0 :(得分:2)

选择ID,然后使用它们执行更新。以下是使用您的代码的示例,稍作修改:

$topPeople = SomeModel
    ->select(['id', DB::raw('COUNT(*) as count')])
    ->groupBy('id')
    ->orderBy('count', 'desc')
    ->take(10)
    ->pluck('id');

SomeModel::whereIn('id', $topPeople)->update(['popular' => 1]);