Laravel:如何将原始查询转换为“查询构建器”或“Eloquent”查询

5

我有一个Laravel查询构建器片段,它运行良好:

$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);

有没有避免使用原始查询但仍能得到相同结果的方法?换句话说,我如何以更符合“查询构建器”风格的方式编写此查询?我能否将其转换为Eloquent查询?
谢谢。
1个回答

6
你可以使用 selectSub 方法进行查询。
(1)首先创建角色查询。
$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) 其次,将$role子查询添加为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);

输出SQL语法

"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"

哦,selectSub()!!!为什么文档中没有提到它??? :-/ 我还看到了whereRaw()的东西:使用原始查询是实现结果的唯一方法吗?我尽可能想避免使用原始查询... - Ivan
@Ivan,你可以使用普通的 where 方法,并使用 Illuminate\Database\Query\Expression。将 whereRaw('users.id = role_users.user_id') 转换为 where('users.id', '=', new Illuminate\Database\Query\Expression('role_users.user_id')) - Nyan Lynn Htut
非常感谢!:-) - Ivan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接