I have table users and pivot table role_user, not every user has a role. 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? 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. Then within each group users will be ordered by role_id .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.