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

試著忘記壹切 提交于 2019-12-13 11:47:43

问题


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


回答1:


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"


来源:https://stackoverflow.com/questions/36422981/laravel-change-a-raw-query-in-a-query-builder-or-eloquent-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!