我有一个函数,我可以传递类别 ID,并基于该 ID 来获取所有产品。
这是我的数据库的结构
类别数据库:
category_name
产品数据库:
product_name;
类别产品:
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个查询)
$products = Product::whereHas('categories', function($qbCategory) use($categoryId) {
$qbCategory->where('id',$categoryId);
})->get();
关于php - 使用数据透视表按类别 ID 获取产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68015883/