Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: change a raw query in a "query-builder" or "eloquent" one

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

like image 908
Ivan Avatar asked Apr 05 '16 09:04

Ivan


1 Answers

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"
like image 94
Nyan Lynn Htut Avatar answered Nov 05 '22 20:11

Nyan Lynn Htut