简体   繁体   English

Laravel按角色订购用户

[英]Laravel order user by role

I have table users and pivot table role_user, not every user has a role. 我有表用户和数据透视表role_user,不是每个用户都有一个角色。 I need to make a query and get all users, and order them by roles, which join statement should I use then, how would that query look like then? 我需要进行查询并获得所有用户,并按角色对其进行排序,然后我应该使用哪个join语句,那么该查询将是什么样子? I need some similar query to this, but so that users with that have roles come first and not the ones that don't have roles like now: 我需要与此类似的查询,但要使拥有角色的用户优先而不是像现在这样没有角色的用户:

$users = DB::table('users')
                     ->leftJoin('role_user', 'users.id', '=', 'role_user.user_id')
                     ->orderBy('role_id')
                     ->get();

The following code should do the trick: 以下代码可以解决问题:

$users = DB::table('users')
  ->leftJoin('role_user', 'users.id', '=', 'role_user.user_id')
  ->orderBy(\DB::raw('role_id IS NULL'))
  ->orderBy('role_id')
  ->get();

This way you'll first sort by role_id IS NULL , that will be 0 if user has role_id set and 1 if user has no role, so users with role set will go first. 这样,您将首先按role_id IS NULL排序,如果用户设置了role_id ,则为0,如果用户没有角色,则为1 ,因此具有角色集的用户将排在第一位。 Then within each group users will be ordered by role_id . 然后,在每个组中,将按role_id对用户进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM