【问题标题】:Laravel 5.2: get models belonging to multiple modelsLaravel 5.2:获取属于多个模型的模型
【发布时间】:2016-04-12 12:38:39
【问题描述】:

我有两个表和一个数据透视表:

Table1: products
id
name

Table2: categories
id
name
parent

Pivot table: product_categories
product_id
category_id

Relationship between them is:

    product belongsToMany category (trough product_categories)
    category belongsToMany product (trough product_categories)

如果它的主类别,则parent为0,否则是一个整数,表示另一个类别的id。我有一个类别 ID,它可能有也可能没有子类别,并且可能是 0 或更多。

我需要属于该类别及其子类别的产品列表。 (如果没有选择类别,那么简单:需要列出所有产品)

目前我有一个数组(或集合)中类别的 id 列表:

$w = [];
$w['parent'] = (!empty($id)?$id:0);
$categories = Category::where('id', $w['parent'])->orWhere($w)->get()->toArray();

我怎样才能优雅地做到这一点?任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel eloquent relationship has-and-belongs-to-many


    【解决方案1】:

    您可以向类别模型添加 oneToMany 关系:

        public function subcategories()
        {
            return $this->hasMany('\App\Category', 'parent_id');
        }
    

    【讨论】:

      【解决方案2】:

      我终于得到了答案,这就是我的解决方法:

      $category_ids = Category::where('user_id', $user->id)->where('id', $id)->orWhere(['parent'=>$id])->pluck('id')->toArray();
      $category_ids = array_unique($category_ids);
      
      $product_ids = ProductCategory::whereIn('category_id', $category_ids)->pluck('product_id')->toArray();
      $product_ids = array_unique($product_ids);
      
      $products = Product::where('user_id', $user->id)->whereIn('id', $product_ids)->paginate(12);
      

      只要类别最多有 2 个级别,就可以。

      【讨论】:

        猜你喜欢
        • 2016-07-25
        • 2016-04-09
        • 2016-09-05
        • 2017-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        相关资源
        最近更新 更多