[英]laravel 5 nested category and nested sub category
使用Laravel 5.6,我试图显示MySQL类别表中子类别的子类别。 我想传递名称并获得所有子类别,而与父类别无关。
类别表
id | name | cat_parent_id
--- | ------------------| -------------
1 | Parent - 1 | NULL
2 | Parent - 2 | NULL
3 | Child-1- P - 1 | 1
4 | Child-1- P - 2 | 2
5 | sCh-1-Ch-1-P- 2 | 4
6 | sCh-2-Ch-1-P- 2 | 4
7 | sCh-3-Ch-1-P- 2 | 4
8 | sCh-4-Ch-1-P- 2 | 4
9 | sCh-5-Ch-1-P- 2 | 4
所需结果
返回App \\ Category :: where('name','Child-1- P-2')-> Children-> get();
id | name | cat_parent_id
--- | ------------------| -------------
5 | sCh-1-Ch-1-P- 2 | 4
6 | sCh-2-Ch-1-P- 2 | 4
7 | sCh-3-Ch-1-P- 2 | 4
8 | sCh-4-Ch-1-P- 2 | 4
9 | sCh-5-Ch-1-P- 2 | 4
如果我了解得很好,则可以在App\\Category
模型上使用以下方法来获得children
关系:
// app/Category.php
public function children(): HasMany
{
return $this->hasMany(static::class, 'cat_parent_id', 'id');
}
然后获得主要类别的所有子代:
use App\Category;
$children = Category::where('name','Child-1- P - 2')->first()->children;
这是一家工厂的辅助测试:
// database/factories/CategoryFactory.php
use App\Category;
$factory->define(Category::class, function (Faker $faker) {
static $id = 1;
return [
'name' => 'Category '.$id++,
'cat_parent_id' => null,
];
});
// tests/Unit/Models/CategoryTest.php
use App\Category;
/**
* @test
*/
public function returns_associated_child_records()
{
// create master records
factory(Category::class, 3)->create();
// get parent for the sub-categories
$parent = $master->first();
// create sub-categories
foreach(range(1, 4) as $id) {
factory(Category::class)->create([
'name' => 'Sub category '.$id,
'cat_parent_id' => $parent->id
]);
}
$this->assertEquals(
['Sub category 1', 'Sub category 2', 'Sub category 3', 'Sub category 4'],
Category::where('name', $parent->name)->first()->children->pluck('name')->toArray()
);
}
我在这里假设类别名称将是唯一的-否则您将不得不遍历记录的集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.