Search code examples
laravellaravel-5laravel-5.3

Why query returns empty collection?


I have the following query was built by Laravel:

$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());

The code above gives me empty collection: dd($res->get());.

The plain SQL code of this query is:

    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

If execute this directly in MySQL, I get two result rows.

But why dd($res->get()); retuns me empty?


Solution

  • I don't think there is a whereExists in eloquent model... try this:

    $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();