我正在尝试从一个类别及其所有子类别中检索产品。
这是我的categories桌子:
| id | parent_id | name |
|---- |----------- |------------- |
| 1 | NULL | Electronics |
| 2 | 1 | Computers |
| 3 | 2 | Accessories |
| 4 | 3 | Keyboards |
这是我的产品表:
| id | category_id | name |
|---- |------------- |----------- |
| 1 | 2 | Product 1 |
| 2 | 3 | Product 2 |
| 3 | 4 | Product 3 |
假设我在Computers类别页面中,我想显示此表中的产品以及所有产品。
所以它应该首先从Computersand Accessoriesand also获取产品Keyboards。
这是我的类别模型:
public function parent() {
return $this->belongsTo(Category::class, 'parent_id');
}
public function childs() {
return $this->hasMany(Category::class, 'parent_id');
}
public function products() {
return $this->hasManyThrough(Product::class, Category::class, 'parent_id', 'category_id', 'id');
}
产品型号:
public function categories() {
return $this->belongsTo(Category::class, 'category_id');
}
查询:
Category::with(['products', 'childs.products'])->where('id', $category->id)->get();
返回:
{
"id":11,
"parent_id":4,
"name":"Computers",
"products":[
{
"id":2,
"category_id":12,
"title":"Product 1",
"laravel_through_key":11
}
],
"childs":[
{
"id":12,
"parent_id":11,
"name":"Accessories",
"products":[
{
"id":1,
"category_id":13,
"user_id":1,
"title":"Product 2",
"laravel_through_key":12
}
]
}
]
}
上面,它正在转义最后一个子类别Keyboards。
我曾尝试使用hasManyThrough关系,但我只得到了产品Computers,Accessories但没有达到Keyboards。
因此,如果我在一个类别中,我想从该类别树中获取所有产品。即使一个子类别有子类别。
我怎样才能做到这一点?
郎朗坤
慕神8447489
尚方宝剑之说
www说