intelis intelis - 2 months ago 12
PHP Question

Laravel Eloquent data ranking

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

Answer

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.
Comments