[英]Laravel get all records who have category
所以我一直在努力解决这个问题。 我不想获得包含某个枢轴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();
此外,我的方式返回一个数组,而不是一个集合,所以我甚至无法达到我的刀片中的类别。
我希望有人可以帮助我。
谢谢!
有一个更好的方式,你很接近......
$products = Product::with('categories')
->whereHas('categories', function($q) use ($categoryUrl) {
$q->where('title', $categoryUrl);
})->get();
您可能需要在Category模型中实现belongsToMany方法,以便将属于此特定传递类别的所有产品集合一起返回。
// Category.php
public function products()
{
return $this->belongsToMany(Product::class);
}
在控制器中使用:
$products = Category::with('products')->where('title', $categoryName)->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.