所以我已经为此苦苦挣扎了一段时间。
我不想获取所有包含特定数据透视表 category
的“产品”。
所以我有一条路线:
Route::get('products/{category}', ['as' => 'category.products', 'uses' => 'ProductsController@getCatProducts']);
还有一个产品模型:
public function categories()
{
return $this->belongsToMany(Category::class);
}
然后是我的 Controller :
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 中的类别。
我希望有人能帮助我。
谢谢!
最佳答案
有一个更好的方法,而且你很接近...
$products = Product::with('categories')
->whereHas('categories', function($q) use ($categoryUrl) {
$q->where('title', $categoryUrl);
})->get();
关于php - Laravel 获取所有具有类别的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38145475/