2014-10-10 42 views
5

我試圖從user_groups數據透視表中的某個用戶組中匹配users表中的所有用戶。即時通訊從Cartalyst btw使用Sentry 2。Laravel - 帶連接和concat的Querybuilder

這可以讓所有用戶名字和姓氏連接在一起。

User::select(DB::raw('CONCAT(last_name, ", ", first_name) AS full_name'), 'id') 
     ->where('activated', '=', '1') 
     ->orderBy('last_name') 
     ->lists('full_name', 'id'); 

當我嘗試將其更改爲也過濾不屬於某個組的用戶時出現語法錯誤。

User::select(DB::raw('SELECT CONCAT(user.last_name, ", ", user.first_name) AS user.full_name'), 'user.id', 'users_groups.group_id', 'users_groups.user_id') 
         ->join('users_groups', 'user.id', '=', 'users_groups.user_id') 
         ->where('user.activated', '=', '1') 
         ->where('users_groups.group_id', '=', $group) 
         ->orderBy('user.last_name') 
         ->lists('user.full_name', 'user.id'); 

任何在正確的方向微調將不勝感激。

編輯:語法錯誤

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in 
your SQL syntax; check the manual that corresponds to your MySQL server 
version for the right syntax to use near 'SELECT CONCAT(user.last_name, ", ", 
user.first_name) AS user.full_name, `user`.`' at line 1 (SQL: select SELECT 
CONCAT(user.last_name, ", ", user.first_name) AS user.full_name, `user`.`id`, 
`users_groups`.`group_id`, `users_groups`.`user_id` from `users` inner join 
`users_groups` on `user`.`id` = `users_groups`.`user_id` where 
`users`.`deleted_at` is null and `user`.`activated` = 1 and 
`users_groups`.`group_id` = 9 order by `user`.`last_name` asc) 
+0

你可以添加語法錯誤? – 2014-10-10 20:06:59

+0

將錯誤添加到問題中。謝謝 – MDS 2014-10-10 20:12:04

回答

8

Logan的回答讓我開始朝着正確的方向發展。我也必須刪除所有的'用戶'。因爲它已經調用Users模型了,所以我想。此查詢工作:

User::select(DB::raw('CONCAT(last_name, ", ", first_name) AS full_name'), 'id') 
         ->join('users_groups', 'id', '=', 'users_groups.user_id') 
         ->where('activated', '=', '1') 
         ->where('users_groups.group_id', '=', $group) 
         ->orderBy('last_name') 
         ->lists('full_name', 'id'); 

謝謝大家!希望如果有人遇到這個問題,他們會找到這個問題的指導。

+1

你不需要從數據透視表中選擇任何東西。 – 2014-10-10 20:39:12

+0

Good call @JarekTkaczyk。編輯答案。 – MDS 2014-10-10 20:45:09

1

在第二個例子中,你有DB::raw('SELECT ...')。您需要刪除'SELECT'關鍵字。

0

通過查詢生成器,你可以這樣做:

DB::table('users')->join('...')->where('...') ->lists(DB::raw('CONCAT(firstname, " ", lastname)'), 'id')

6

你不需要在DB選擇::生(),見例如

User::select(
      'id', 
      DB::raw('CONCAT(first_name," ",last_name) as full_name') 

     ) 
     ->orderBy('full_name') 
     ->lists('full_name', 'id');