2016-04-12 33 views
1

我有两个表和数据透视表款获得:Laravel 5.2:属于多种模式

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) 

如果它的主要类别,比父母是0,否则为代表的其他类别的ID的整数。我有一个类别ID,可能有也可能没有子类别,可能是0或更多。

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

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

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

我怎样才能以优雅的方式做到这一点?任何帮助都会有所帮助。

回答

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级,这个作品。

0

您可以添加到类型模型一个一对多的关系:

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