doujia1871 2018-05-22 05: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-22 06: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条)

报告相同问题?

悬赏问题

  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启