【发布时间】:2016-04-12 12:38:39
【问题描述】:
我有两个表和一个数据透视表:
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();
我怎样才能优雅地做到这一点?任何帮助将不胜感激。
【问题讨论】:
标签: php laravel eloquent relationship has-and-belongs-to-many