Laravel Eloquent - (where)和(where,where where或where)

时间:2017-04-30 11:10:12

标签: php laravel laravel-5 eloquent laravel-eloquent

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

这就是我现在所拥有的:

$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);

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

我该怎么做?

2 个答案:

答案 0 :(得分:4)

您需要将或者电话组合在一起。以下应该可以解决问题:

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.'%');
  });
}

答案 1 :(得分:0)

在“或”位置使用组:

if($search_query != ""){
$clients = Company::where('guid',$guid)->first()
    ->where('is_temp',0)
    ->where(function($query) {
        $query->where('name','LIKE','%'.$search_query.'%')
            ->orWhere('email','LIKE','%'.$search_query.'%')
            ->orWhere('vat_number','LIKE','%'.$search_query.'%')
            ->orWhere('contact_name','LIKE','%'.$search_query.'%')
    })->orderBy('name', $sort_order)
    ->skip($per_page*($page-1))
    ->take($per_page);
}
$response = [
    'clients' => $clients->get() 
];
return response()->json($response, 200);