dongle3217 2013-04-16 14:34
浏览 452
已采纳

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

  • 写回答

2条回答 默认 最新

  • du7133 2013-04-16 23:18
    关注

    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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部