web-dev-qa-db-ja.com

Laravel-結合と連結を備えたクエリビルダー

Users_groupsピボットテーブルの特定のグループに一致するすべてのユーザーをusersテーブルから取得しようとしています。カルタリストのセントリー2を使用しています。

これは、姓と名が連結されたすべてのユーザーを取得するために機能します。

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)
7
MDS

ローガンの答えは私を正しい方向に導きました。また、「ユーザー」もすべて削除する必要がありました。プレフィックスは、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');

みんな、ありがとう!誰かがこれに遭遇した場合、うまくいけば、彼らはこの質問のガイダンスを見つけるでしょう。

15
MDS

DB :: raw()で選択する必要はありません。例を参照してください

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

        )
       ->orderBy('full_name')
       ->lists('full_name', 'id');
11
Majbah Habib

2番目の例では、DB::raw('SELECT ...')があります。 「SELECT」キーワードを削除する必要があります。

1
Logan Bailey

クエリビルダーを使用すると、次のことができます。

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

0
NinoMarconi