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

僤鯓⒐⒋嵵緔 提交于 2019-12-03 15:21:07

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