Multiple where queries, using orWhere, in fields of model and related models

廉价感情. 提交于 2019-12-06 12:20:33

You need to use something like this for all your sets of filters:

`where(function($q){$q->where()->orWhere();})` 

to make those inner wheres wrapped in (...) because by adding simple orWhere you mess up whole query:

// your 2nd query in the incorrect array:
select * from `contact` where `contact`.`deleted_at` is null and
  ((select count(*) from `ecozone` where `ecozone`.`deleted_at` is null 
    and `contact`.`ecozone_id` = `ecozone`.`id` 
    // this is your first where()
    and `ecozone`.`ecozone` LIKE ? 
    // and this is orWhere, which make the query wrong
    or `ecozone`.`ecozone` LIKE ? and `ecozone`.`deleted_at` is null)
  >= 1) limit 10 offset 0

You already did that for top level filters, but not in whereHas


So it should look like this:

} else {
    foreach($filters as $column => $filter) {
        $q->whereHas($model, function ($q) use ($filter, $model, $column) {
            $q->where(function ($q) use ($filter, $model, $column) {
               $first = array_pop($filter);
               $q->where("$model.$column", 'LIKE', "%$first%");
               foreach($filter as $or) {
                   $q->orWhere("$model.$column", 'LIKE', "%$or%");
               }
            });
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!