我创建了多个过滤器餐厅。 这是“餐厅”模型上的类别关系:
public function categories()
{
return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id');
}
这是过滤器餐厅管理员
public function filter(Request $request)
{
// Kiểm tra ajax
if(!$request->ajax())
{
return "";
}
// Lọc theo thành phố & quận
if(!$request->city && !$request->district)
$restaurants = Restaurant::with('categories');
elseif($request->district)
$restaurants = Restaurant::with('categories')->where('district_id', $request->district);
else
$restaurants = Restaurant::with('categories')->where('city_id', $request->city);
// Kiểm tra có tìm kiếm hay ko
if(!empty($request->input('query')))
{
$restaurants = $restaurants->join('restaurant_translations as t', 't.restaurant_id', '=', 'restaurants.id')
->where('t.locale','=', LaravelLocalization::getCurrentLocale())
->where('t.name', 'like', '%'.$request->input('query').'%')
->select('restaurants.*');
}
//Kiểm tra có lọc theo danh mục hay ko
if(!empty($request->input('category')) && $request->input('category') != 0)
{
}
foreach($restaurants->get() as $restaurant) {
}
...
return $html;
}
如果具有请求过滤器类别,我想让餐厅具有categoryID =请求类别ID。我在自己的脚本中做了一些操作,但发现无法正常工作。谁能告诉我该怎么做?非常感谢!
答案 0 :(得分:0)
尝试使用whereHas()
if(!empty($request->input('category')) && $request->input('category') != 0) {
$restaurants->whereHas('category', function (Builder $q) {
$q->where('id', $request->input('category'));
});
}