laravel中链式OR查询

在laravel常用的链式操作中

 

->when(isset($filter['recommend_flag']), function ($query) use ($filter) {
                if (!$filter['recommend_flag']) {
                        $query->Where('recommend_flag', 0)->orWhere('recommend_flag',          2);
                } else {
                    return $query->where('recommend_flag', $filter['recommend_flag']);
                }
            })

 

那么bug出现了 为什么呢

打开sql日志发现

select * from `fb_im_group` where `university_id` > '0' and `university_id` in ('21135') and (`recommend_flag` = '0' or `recommend_flag` = '2') and `recommend_flag` = '0' order by `id` desc limit 20 offset 0

当我想拿`recommend_flag` == 2 的数据时 , 条件是不会过滤`recommend_flag` == 0的

 

那么怎么解决此问题呢  我们需要再一层

->when(isset($filter['recommend_flag']), function ($query) use ($filter) {
                if (!$filter['recommend_flag']) {
                    return $query->where(function ($query) {
                        $query->Where('recommend_flag', 0)->orWhere('recommend_flag', 2);
                    });
                } else {
                    return $query->where('recommend_flag', $filter['recommend_flag']);
                }
            })

仔细观察不同

然后我们再查看sql日志

select * from `fb_im_group` where `university_id` > '0' and `university_id` in ('21135') and (`recommend_flag` = '0' or `recommend_flag` = '2') order by `id` desc limit 20 offset 0

这才是我想要的结果

你可能感兴趣的:(解决方案)