5

I have this Laravel Query Builder snippet that is working fine:

$records = DB::table('users')
    ->select(
        DB::raw('users.*, activations.id AS activation, 
                 (SELECT roles.name FROM roles 
                  INNER JOIN role_users 
                    ON roles.id = role_users.role_id
                  WHERE users.id = role_users.user_id LIMIT 1) 
                  AS role')
    )
    ->leftJoin('activations', 'users.id', '=', 'activations.user_id')
    ->where('users.id', '<>', 1)
    ->orderBy('last_name')
    ->orderBy('first_name')
    ->paginate(10);

Is there a way to avoid use of raw queries and get the same result? In other words, how can I write this in a more "query-builder" style? Can I also translate this into an Eloquent query?

Thanks

abbood
  • 23,101
  • 16
  • 132
  • 246
Ivan
  • 2,463
  • 6
  • 39
  • 51

1 Answers1

6

You can used selectSub method for your query.

(1) First create the role query

$role = DB::table('roles')
            ->select('roles.name')
            ->join('roles_users', 'roles.id', '=', 'role_users.role_id')
            ->whereRaw('users.id = role_users.user_id')
            ->take(1);

(2) Second added the $role sub query as role

DB::table('users')
                ->select('users.*', 'activations.id AS activation')
                ->selectSub($role, 'role') // Role Sub Query As role
                ->leftJoin('activations', 'users.id', '=', 'activations.user_id')
                ->where('users.id', '<>', 1)
                ->orderBy('last_name')
                ->orderBy('first_name')
                ->paginate(10);

Output SQL Syntax

"select `users`.*, `activations`.`id` as `activation`, 
(select `roles`.`name` from `roles` inner join `roles_users` on `roles`.`id` = `role_users`.`role_id` 
where users.id = role_users.user_id limit 1) as `role` 
from `users` 
left join `activations` on `users`.`id` = `activations`.`user_id` 
where `users`.`id` <> ? 
order by `last_name` asc, `first_name` asc 
limit 10 offset 0"
Nyan Lynn Htut
  • 657
  • 1
  • 8
  • 10
  • Oh, selectSub()!!! Why it's not mentioned anywhere in the docs??? :-/ I also see the whereRaw() stuff: using that raw query is the only way to achieve the result? I'd like to avoid raw queries as much as possible... – Ivan Apr 08 '16 at 10:36
  • @Ivan You can used normal `where` method with using `Illuminate\Database\Query\Expression`. `whereRaw('users.id = role_users.user_id')` to `where('users.id', '=', new Illuminate\Database\Query\Expression('`role_users`.`user_id`'))` – Nyan Lynn Htut Apr 08 '16 at 11:16
  • Thanks really a lot! :-) – Ivan Apr 08 '16 at 14:29