我有两个表和一个数据透视表:
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 回答
您可以向类别模型添加oneToMany关系:
我终于得到了答案,这就是我解决的问题:
只要类别最多有2个级别,就可以了 .