gpt4 book ai didi

php - 搜索多个字段laravel的最佳方式

转载 作者:行者123 更新时间:2023-12-03 21:22:52 27 4
gpt4 key购买 nike

我尝试使用 8 个字段创建一个搜索函数。我在底部使用这种方式
但它的返回任何报价都具有此给定值之一。
我想要的是他拥有所有值(value)的报价。
用户可以使用他想要的任何字段进行搜索
如果没有很多条件,最好的方法是什么

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

编辑 whereBetween:
$projects = Project::

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

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

关于php - 搜索多个字段laravel的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51537381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com