Laravel Eloquent - (where) and (where or where or where)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43705728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:53:08  来源:igfitidea点击:

Laravel Eloquent - (where) and (where or where or where)

phplaravellaravel-5eloquentlaravel-eloquent

提问by Ilan Finkel

I'm working on a search query for my data, I want to get only the available rows which are those who have value 0 in is_tempcolumn and if the user send me a search query i would like to search this value in other columns

我正在对我的数据进行搜索查询,我只想获取列中值为 0 的可用行,is_temp如果用户向我发送搜索查询,我想在其他列中搜索此值

this is what I have now:

这就是我现在所拥有的:

$clients = Company::where('guid',$guid)->first()
        ->clients()
        ->where('is_temp',0)
        ->orderBy('name', $sort_order)
        ->skip($per_page*($page-1))
        ->take($per_page);

if($search_query != ""){
     $clients = $clients->orWhere('name','LIKE','%'.$search_query.'%')
                        ->orWhere('email','LIKE','%'.$search_query.'%')
                        ->orWhere('vat_number','LIKE','%'.$search_query.'%')
                        ->orWhere('contact_name','LIKE','%'.$search_query.'%');
}

$response = [
    'clients' => $clients->get() 
];
return response()->json($response, 200);

but when I use it this way I get also the rows that the field is_tempequal to 1 so I need to use (where) and (where or where or where...)

但是当我以这种方式使用它时,我也会得到字段is_temp等于 1的行,所以我需要使用 (where) 和 (where 或 where 或 where...)

how do i do that?

我怎么做?

回答by jedrzej.kurylo

You need to group the orWherecalls together. The following should do the trick:

您需要将orWhere调用组合在一起。以下应该可以解决问题:

if($search_query != ""){
  $clients = $clients->where(function($query) use ($search_query) {
    $query->where('name','LIKE','%'.$search_query.'%')
          ->orWhere('email','LIKE','%'.$search_query.'%')
          ->orWhere('vat_number','LIKE','%'.$search_query.'%')
          ->orWhere('contact_name','LIKE','%'.$search_query.'%');
  });
}