2017-02-26 4 views
0

私は次のクエリは、Laravelにより建設された持っている:dd($res->get());:上記のコードは私の空のコレクションを提供しますなぜクエリが空のコレクションを返すのですか?

$res = Announcement::whereExists(function ($query) { 
       $query->select(DB::raw(1)) 
        ->from('announcement_category')->join('user_category', 'user_category.category_id', '=', 'announcement_category.category_id') 
        ->where('user_category.user_id', '=', 1) 
        ->where('announcement_category.announcement_id', '=', 'announcements.id'); 
      }); 

dd($res->get()); 

このクエリのプレーンなSQLコードは次のとおりです。

select * from `announcements` where exists (select 1 from 
`announcement_category` inner join `user_category` on 

`user_category`.`category_id` = `announcement_category`.`category_id` where `user_category`.`user_id` = 1 

and `announcement_category`.`announcement_id` = announcements.id) 

and `announcements`.`deleted_at` is null 

のMySQLに直接これを実行すると、私は2つの結果行を取得します。

しかし、なぜdd($res->get());が空を返すのですか?

+0

は、なぜあなたは 'DB ::生(1)'でSELECT句を使用しましたか? – mrabbani

+0

'*' resultを使用する場合は、同じ – Darama

答えて

1
私は雄弁なモデルでwhereExistsがあるとは思わない

...これを試してみてください。

$res = DB::table('announcement')->whereExists(function ($query) { 
       $query->select(DB::raw(1)) 
        ->from('announcement_category')->join('user_category', 'user_category.category_id', '=', 'announcement_category.category_id') 
        ->where('user_category.user_id', '=', 1) 
        ->where('announcement_category.announcement_id', '=', 'announcements.id'); 
      })->get(); 
+0

があります。[link](https://laravel.com/api/5.4/Illuminate/Database/Query/Builder.html#method_whereExists) – d1c1pl3

関連する問題