I am trying to range users, based on how many rows there are in the DB with ther id.
My dataset look like this (simplified):
A .... John
A .... John
B .... Mike
A .... John
B .... Mike
C .... Denis
I want first three unique names, ordered by how many times a value on the left appears.
Can I do that with Laravel's eloquent ORM?
A result would then be:
John
Mike
Denis
Thanks
That's how you do it with Laravel's Eloquent ORM
Model::select('name')
->groupBy('name')
->orderBy(DB::raw('count(name)'), 'desc')
->take(3)
->get();
If you are using Laravel 3 then use snake case:
Model::select('name')->group_by('name')->order_by(DB::raw('count(name)'), 'desc')->take(3)->get();
If you wish you may just use Query Builder (Fluent) by using DB::table('tableName')->
instead of Model::
.
Notes:
DB::raw()
instructs Laravel not to put backtics there.take()
limits the rows.Not a laravel solution, but it might work (pure SQL, specifically MySQL):
select name
from yourTable
where ... # Your filter conditions go here
group by name
order by count(id) desc
limit 3;
Hope this helps