2

我有一个函数,我在其中传递类别 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);
    }

我已经测试了多个查询,但对我的情况没有任何作用。

4

1 回答 1

2

您可以通过两种不同的方式进行操作

验证类别是否存在的间接方式(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();
于 2021-06-17T08:52:58.453 回答