laravel多字段模糊查找,用when+orwhere时其他条件失效

Posted 酸辣柠檬粉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了laravel多字段模糊查找,用when+orwhere时其他条件失效相关的知识,希望对你有一定的参考价值。

多字段查询时 ,关键字模糊查找$keywords,使用when条件+orwhere时,其他where条件失效

 使用出来的sql语句为

 select count(*) as aggregate from `gwgl_buyers` where (exists (select * from `gwgl_users` where `gwgl_buyers`.`user_id` = `gwgl_users`.`id` and `nickname` like %4000% and `gwgl_users`.`deleted_at` is null) and `identity` = 1 and `nickname` like %100% or `account` like %100% or `tel` like %100% or `QQ` like %100% or `wechat` like %100%) and `gwgl_buyers`.`deleted_at` is null)

 

很明显 like语句 需要阔起来作为and的其中一个条件

select count(*) as aggregate from `gwgl_buyers` where `identity` = 1 and (`nickname` like %100% or `account` like %100% or `tel` like %100% or `QQ` like %100% or `wechat` like %100%) and exists (select * from `gwgl_users` where `gwgl_buyers`.`user_id` = `gwgl_users`.`id` and `nickname` like %4000% and `gwgl_users`.`deleted_at` is null) and `gwgl_buyers`.`deleted_at` is null)

修改when语句为where语句就ok了

$list = Buyer::with(['tag','origin','user'=>function($query){
                $query->select('id','nickname');
            }])
            ->when($tag,function($query,$tag){
                return $query->where('tag_id',$tag);
            })
            ->when($origin,function($query,$origin){
                return $query->where('origin_id',$origin);
            })
            ->where('identity',1)
            ->where(function($query) use($keywords){
                $query->where('nickname','like','%'.$keywords.'%');
                $query->orWhere('account','like','%'.$keywords.'%');
                $query->orWhere('tel','like','%'.$keywords.'%');
                $query->orWhere('QQ','like','%'.$keywords.'%');
                $query->orWhere('wechat','like','%'.$keywords.'%') ;
            })
            ->whereHas('user',function(Builder $query) use($manager){
                $manager && $query->where('nickname','like','%'.$manager.'%');
            })
            ->paginate($limit);

 

 

以上是关于laravel多字段模糊查找,用when+orwhere时其他条件失效的主要内容,如果未能解决你的问题,请参考以下文章

laravel多字段模糊查找,用when+orwhere时其他条件失效

laravel多字段模糊查找,用when+orwhere时其他条件失效

简单实现mysql多字段模糊查询

select case when,用来判断查询

Laravel ORM怎么用where case end?

怎么用linq to sql 写单表多字段的模糊查询方法