我有兩個表和數據透視錶款獲得: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();
我怎樣才能以優雅的方式做到這一點?任何幫助都會有所幫助。