从 2 个数据透视表返回数据

时间:2021-02-03 22:38:46

标签: php laravel eloquent

我的数据库中有 productscategoriessizes 表,并且还有 2 个名为 category_productproduct_size 的数据透视表。 我试图让产品属于特定类别,我需要按尺寸过滤它们。

我已经尝试过这个,但我得到了所有尺寸...

$category = Category::where('slug', $slug)->first();
$products = $category->products()
     ->with('sizes')
     ->whereHas('sizes', function($q) use($size_id) {
        $q->where('size_id', '=', $size_id);
     })
     ->paginate(12);

产品型号

public function categories()
{
    return $this->belongsToMany(Category::class);
}

public function sizes()
{
    return $this->belongsToMany(Size::class);
}

类别模型

public function products()
{
    return $this->belongsToMany(Product::class);
}

尺寸模型

public function products()
{
    return $this->belongsToMany(Product::class);
}

1 个答案:

答案 0 :(得分:0)

whereHas() 将根据急切加载的关系过滤返回的模型,但不会过滤关系本身。如果需要,您需要将它与 with() 的第二个参数配对,如下所示:

$size_id  = 10;
$category = Category::where('slug', $slug)->first();
$products = $category
    ->products()
    ->with('sizes', fn ($q) => $q->where('size_id', $size_id))
    ->whereHas('sizes', fn ($q) => $q->where('size_id', $size_id))
    ->paginate(12);

所以您使用了两次相同的回调,这有点愚蠢,但只能返回所需的数据。