0

I have an eloquent query which returns the 10 most frequently found names in a table.

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

This works fine for returning results but I want to update these records rather than return the data. When I use update instead of get;

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

I get the error;

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'count' in 'order clause'

What is an efficient way of updating the popular field in these records?

1 Answer 1

2

Select the ids, then use those to perform the update. Here's an example using your code, slightly changed:

$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]); 
Sign up to request clarification or add additional context in comments.

1 Comment

pluck! Thats the functionality I was looking for, thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.