使用 pivot table 按类别 ID 获取产品
Fetch products by category id using pivot table
我有一个传递类别 ID 的函数,并基于该函数获取所有产品。
这是我的数据库的结构
类别数据库:
category_name
产品数据库:
product_name;
category_product:
category_id;
product_id;
下面是它们之间的关系
在产品中:
public function categories()
{
return $this->belongsToMany(Category::class);
}
在类别中:
public function products()
{
return $this->belongsToMany(Product::class);
}
我已经测试了多个查询,但对我的情况没有任何效果。
您可以通过两种不同的方式进行
验证类别是否存在的间接方式(2 个查询)
$category = Category::with('products')->findOrFail($categoryId);
// you can also do without the with(); only one id, so no benefit for the eager load
// $category = Category::findOrFail($categoryId);
$products = $category->products;
直接方式,如果类别不存在(但没有消息)(1 个查询),return 将是一个空集合
$products = Product::whereHas('categories', function($qbCategory) use($categoryId) {
$qbCategory->where('id',$categoryId);
})->get();
我有一个传递类别 ID 的函数,并基于该函数获取所有产品。
这是我的数据库的结构
类别数据库:
category_name
产品数据库:
product_name;
category_product:
category_id;
product_id;
下面是它们之间的关系
在产品中:
public function categories()
{
return $this->belongsToMany(Category::class);
}
在类别中:
public function products()
{
return $this->belongsToMany(Product::class);
}
我已经测试了多个查询,但对我的情况没有任何效果。
您可以通过两种不同的方式进行
验证类别是否存在的间接方式(2 个查询)
$category = Category::with('products')->findOrFail($categoryId);
// you can also do without the with(); only one id, so no benefit for the eager load
// $category = Category::findOrFail($categoryId);
$products = $category->products;
直接方式,如果类别不存在(但没有消息)(1 个查询),return 将是一个空集合
$products = Product::whereHas('categories', function($qbCategory) use($categoryId) {
$qbCategory->where('id',$categoryId);
})->get();