Php 搜索多个字段的最佳方法laravel

Php 搜索多个字段的最佳方法laravel,php,ajax,laravel,Php,Ajax,Laravel,我尝试使用8个字段创建一个搜索函数。我用这种方式在底部 但它的回报是,任何报价都有一个给定的值。 我想要的是他提供的所有价值观。 用户可以搜索他想要的任何字段 在没有很多条件的情况下,如果 public function search(Request $request) { $hashids = new Hashids(); $city = $request->city; $category = $r

我尝试使用8个字段创建一个搜索函数。我用这种方式在底部 但它的回报是,任何报价都有一个给定的值。 我想要的是他提供的所有价值观。 用户可以搜索他想要的任何字段 在没有很多条件的情况下,如果

 public function search(Request $request)
        {
            $hashids = new Hashids();
            $city = $request->city;
            $category = $request->category;
            $type = $request->type;
            $rooms = $request->rooms;
            $minPrice = $request->minPrice;
            $maxPrice = $request->maxPrice;
            $minSpace = $request->minSpace;
            $maxSpace = $request->maxSpace;
            $citySearch = DB::table('offers')->where('city',$city);
            $categorySearch = DB::table('offers')->where('category_id',$category);
            $typeSearch = DB::table('offers')->where('type',$type);
            $roomsSearch = DB::table('offers')->where('rooms',$rooms);
            $priceSearch = DB::table('offers')
                ->whereBetween('price', [$minPrice, $maxPrice]);
            $spaceSearch = DB::table('offers')
                ->whereBetween('space', [$minSpace, $maxSpace]);
            $result_search = $citySearch->union($categorySearch)->union($typeSearch)->union($roomsSearch)->union($priceSearch)->union($spaceSearch)->get();
            $view = View::make('ajax.search',compact('result_search','hashids'))->render();
            return response()->json(['html'=>$view]);
        }

如果将此搜索用作筛选可能性的方法,则可以采用此方法,只要设置了输入,此方法仅对查询应用条件

这还可以将查询简化为一个查询,而不必合并许多查询:

$projects = Project::

when($request->year_from, function($query) use ($request){
    $query->where('delivery_year', '>=', $request->year_from);
})
->when($request->year_to, function($query) use ($request){
    $query->where('delivery_year', '<=', $request->year_to);
})
->when( $request->delivery_month_from, function($query) use ($request){
    $query->where('delivery_month', '>=', $request->delivery_month_from);
})
->when( $request->delivery_month_to, function($query) use ($request){
    $query->where('delivery_month', '<=', $request->delivery_month_to);
})
->when( $request->product_group, function($query) use ($request){
    $query->whereHas('products', function($q) use ($request) {
        $q->whereHas('group', function($qi) use ($request){
            $qi->whereIn('id', $request->product_group);
        });
    });
})
->get();

这将检查$minSpace和$maxSpace是否都已设置且大于零(等于true)

如“WHERE field=value and otherfield=value and…”?如果字段为空怎么办!我正在工作,但我有一个问题,如何使用whereBetween()函数的这种方式
$projects = Project::

when(($minSpace && $maxSpace), function($query) {
    $query->whereBetween('space', [$minSpace, $maxSpace]);
})->get()