我有两个表和数据透视表款获得: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();
我怎样才能以优雅的方式做到这一点?任何帮助都会有所帮助。