【问题标题】:Laravel eloquant belongsToMany get records belongs to relationshipLaravel eloquent belongsToMany 获取记录属于关系
【发布时间】:2020-10-01 14:25:44
【问题描述】:

我使用 product_product_category 数据透视表与 productsproduct_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();

但我得到了所有的产品。如果您能为我提供解决方案,那将是一个很大的帮助。

【问题讨论】:

    标签: eloquent laravel-7


    【解决方案1】:

    最后,我用 whereHas 找到了答案。为提出相同问题的任何人添加答案。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-04
      • 2022-01-15
      • 2017-02-09
      • 2023-03-28
      • 2015-07-23
      • 2021-08-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多