Laravel Eloquant属于很多获取记录属于关系

时间:2020-10-01 14:25:44

标签: eloquent laravel-7

我正在使用 product_product_category 数据透视表与产品 product_categories 表建立多对多关系。

产品型号

class Product extends Model
{
    public function product_categories() {
        return $this->belongsToMany(ProductCategory::class, 'product_product_category');
    }
}

ProductCategory模型

class ProductCategory extends Model {

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

}

我需要做的是,当我提供了一个类别列表,而只需要获得具有这些类别的产品时。这是我的代码

$selectedCategotries = array(1, 2);
$products = Product::with(['product_categories' => function($q) use ($selectedCategotries){
    $q->whereIn('product_categories.id', $selectedCategotries);
}])->get();

但是我取而代之的是所有产品。如果您能为我提供解决方案,那将是很大的帮助。

1 个答案:

答案 0 :(得分:0)

最后,我找到了哪里有的答案。为遇到相同问题的任何人添加答案。

$products = Product::whereHas('product_categories', function ($q) use ($selectedCategotries) {
    $q->whereIn('product_categories.id', $selectedCategotries);
})->get();