为什么查询返回空集合?

时间:2017-02-26 12:02:08

标签: laravel laravel-5 laravel-5.2 laravel-5.3

我有以下查询是由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());

上面的代码为我提供了空集: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中执行此操作,我会得到两个结果行。

但为什么dd($res->get());会让我空虚?

1 个答案:

答案 0 :(得分: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();