搜索多个字段的最佳方法

时间:2018-07-26 11:07:40

标签: php ajax laravel

我尝试使用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]);
        }

1 个答案:

答案 0 :(得分:3)

如果您使用此搜索来过滤可能性,则可以采用这种方法,只要设置了输入,该方法仅将条件应用于查询。

这也将它简化为一个查询,而不必合并很多查询:

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

在以下位置之间编辑:

$projects = Project::

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

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