2016-04-05 79 views
2

我有這個Laravel查詢生成器片段,做工精細更改原始查詢: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

您可以使用您的查詢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" 
+0

哦,selectSub( )!爲什麼在文檔中沒有提到它? : -/ 我也看到whereRaw()的東西:使用該原始查詢是實現結果的唯一方法?我想盡可能地避免原始查詢... – Ivan

+0

@Ivan您可以使用普通的'where'方法並使用'Illuminate \ Database \ Query \ Expression'。 where'('users.id','=',new Illuminate \ Database \ Query \ Expression('role_users'.'user_id'')where' )' –

+0

非常感謝! :-) – Ivan