Laravel 5.5 WhereIn查询为null

时间:2018-02-22 10:26:19

标签: laravel laravel-5 laravel-5.5

return $places = Place::where('name', 'like', '%' . $request->name . '%')
            ->whereHas('eatCategories', function($q) use($kitchen){
                $q->WhereIn('eat_category_id', $kitchen);
            })
            ->whereHas('services', function($q) use($service){
                $q->WhereIn('service_id', $service);
            })
            ->whereHas('paymentMethods', function($q) use($payment){
                $q->WhereIn('place_attribute_id', $payment);
            })->get();

我的查询正在运行,但如果变量为空,则在所有变量都已满之前查询无效。

$q->WhereIn('eat_category_id', $kitchen);

如果$kitchen为空,我该如何恢复查询?

我的路线:

Route::get('/filter-places/{name?}/{kitchen?}/{service?}/{payment?}', 'SystemController@filterPlaces');

1 个答案:

答案 0 :(得分:2)

一个简单的if内部会做我认为的伎俩:

 $places = Place::where('name', 'like', '%' . $request->name . '%');
 if($kitchen) {
     $places->whereHas('eatCategories', function($q) use($kitchen){
        $q->WhereIn('eat_category_id', $kitchen);
     })
 }
 if($service) {
     $places->whereHas('services', function($q) use($service){
        $q->WhereIn('service_id', $service);
     })
 }
 if($payment) {
     $places->whereHas('paymentMethods', function($q) use($payment){
        $q->WhereIn('place_attribute_id', $payment);
     })
 }
 return $places->get();