Laravel 按类别 ID 过滤餐厅

Laravel filter Restaurants by Category ID

我正在创建多个过滤器餐厅。 这是 Restaurant 模型上的类别关系:

public function categories()
{
    return $this->belongsToMany(Category::class,'restaurant_categories_relation','restaurant_id');
}

这是过滤器 Restaurant Controller

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。我在我的脚本中做了一些事情,但它看起来不起作用。谁能告诉我怎么做?非常感谢!

尝试使用whereHas()

if(!empty($request->input('category')) && $request->input('category') != 0) {
    $restaurants->whereHas('category', function (Builder $q) {
        $q->where('id', $request->input('category'));
    });
}