Laravel Eloquent数据排名
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
我正在尝试根据数据库中有多少行来定位用户。
我的数据集看起来像这样(简化): p>
A .... John
A .... John
B .... Mike
A .... John
B .... Mike
C .... Denis
code> pre>
我想要前三个唯一名称,按左边的值出现的次数排序 。
我能用Laravel雄辩的ORM做到吗? strong> p>
结果将是: p>
John
Mike
Denis
code> pre>
谢谢 p>
div>
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