doujia1871 2018-05-21 21:58
浏览 134
已采纳

使用laravel使用2列查询排序

Here is the sample of my database structure:

id |    name    |   role   |   login_status   |
-----------------------------------------------
 1      mark        user           1
 2      john       lawyer          0
 3      david       user           0
 4      erik       lawyer          0

What I want is to order them in such a way that the users with the lawyer role will be on the top of the list followed by the users with the value of 1 in the login_status column.

I used orderBy('login_status','desc') for the login_status column but i am having a hard time with the condition of the role column.

expected output:

- john
- erik
- mark
- david

Any help would be appreciated. Thanks.

  • 写回答

2条回答 默认 最新

  • doudai8783 2018-05-21 22:01
    关注

    You could use a case expression for you criteria

    ->orderByRaw("CASE WHEN role ='lawyer' THEN 1 ELSE 0 END DESC")
    ->orderBy( 'login_status', 'DESC' );
    

    Plain sql would be like

    select *
    from demo
    order by CASE WHEN role ='lawyer' THEN 1 ELSE 0 END DESC, login_status DESC
    

    Demo

    Or you can make your order clause even shorter like

    order by role ='lawyer' DESC, login_status DESC
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部