我已经苦恼了一段时间了。我想要获取所有包含特定枢轴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中获取类别。
希望有人能帮我解决问题。
谢谢!
belongsToMany
,因为另一端也是一个belongsToMany
。 - user1669496