2016-04-12 37 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'); 
    }