4

所以我一直在努力解决这个问题。我不想得到所有包含某个 pivot 的“产品” category

所以我有一条路线:

Route::get('products/{category}', ['as' => 'category.products', 'uses' => 'ProductsController@getCatProducts']);

和一个产品模型:

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

然后我的控制器:

public function getCatProducts($categoryUrl)
{
    $products = Product::get();

    $productsWithCat = [];

    // loop through all projects
    foreach($products as $product) {

        // loop through all categories assigned to product
        $categories = $product->categories;
        foreach($categories as $category) {

            // check if product has category from url
            if ($category->title == $categoryUrl) {
                array_push($productsWithCat, $product);
            }
        }
    }

    $category = $categoryUrl;
    $products = $productsWithCat;

    return view('pages.category-products', compact('products', 'category'));
}

所以这行得通,但可能有更好的方法来做到这一点。就像是:

$products = Product::with('categories.title', $categoryUrl)->get();

我的方式也返回一个数组而不是一个集合,所以我什至无法访问刀片中的类别。

我希望有人可以帮助我。

谢谢!

4

2 回答 2

4

有一个更好的方法,你很接近......

$products = Product::with('categories')
    ->whereHas('categories', function($q) use ($categoryUrl) {
        $q->where('title', $categoryUrl);
    })->get();
于 2016-07-01T12:33:11.277 回答
1

您可能需要在 Category 模型中实现belongsToMany方法,以便一起返回属于此特定传递类别的所有产品集合。

// Category.php

public function products()
{
    return $this->belongsToMany(Product::class);
}

在控制器中使用:

$products = Category::with('products')->where('title', $categoryName)->get();
于 2016-07-01T13:08:24.743 回答