laravel 5嵌套类别和嵌套子类别

时间:2018-03-31 06:41:15

标签: php laravel-5 categories laravel-eloquent

使用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 

1 个答案:

答案 0 :(得分:2)

如果我理解得很好,要获得children关系,您可以在App\Category模型上使用以下方法:

// 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()
    );
}

我在这里假设类别名称是唯一的 - 否则你必须遍历记录集合。