拉拉维尔获取所有具有类别的记录。

4

我已经苦恼了一段时间了。我想要获取所有包含特定枢轴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();

我的方式现在返回的是一个数组而不是集合,所以我甚至不能在我的Blade中获取类别。

希望有人能帮我解决问题。

谢谢!

2个回答

4

有一种更好的方法,而且你已经接近了...

$products = Product::with('categories')
    ->whereHas('categories', function($q) use ($categoryUrl) {
        $q->where('title', $categoryUrl);
    })->get();

1
你可能需要在Category模型中实现belongsToMany方法,以便一起返回属于该特定类别的所有产品集合。
// Category.php

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

在控制器中使用:

$products = Category::with('products')->where('title', $categoryName)->get();

我认为这应该是一个belongsToMany,因为另一端也是一个belongsToMany - user1669496
是的,你说得对,因为这是多对多的关系,我会编辑我的答案。谢谢。 - hasusuf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接