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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?