首页 文章

Laravel 5.2:获取属于多个模型的模型

提问于
浏览
1

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

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();

我怎样才能以优雅的方式做到这一点?任何帮助都会被贬低 .

2 回答

  • 2

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

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

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

    $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个级别,就可以了 .

相关问题