【发布时间】:2020-10-01 14:25:44
【问题描述】:
我使用 product_product_category 数据透视表与 products 和 product_categories 表使用多对多关系。
产品型号
class Product extends Model
{
public function product_categories() {
return $this->belongsToMany(ProductCategory::class, 'product_product_category');
}
}
产品类别模型
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();
但我得到了所有的产品。如果您能为我提供解决方案,那将是一个很大的帮助。
【问题讨论】: