所以我一直在努力解决这个问题。我不想得到所有包含某个 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();
我的方式也返回一个数组而不是一个集合,所以我什至无法访问刀片中的类别。
我希望有人可以帮助我。
谢谢!