【问题标题】:laravel 5 nested category and nested sub categorylaravel 5 嵌套类别和嵌套子类别
【发布时间】:2018-09-10 02:52:13
【问题描述】:

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

期望的结果

return 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 

【问题讨论】:

  • 问题是什么?有定义children 关系或.. 的问题?
  • 是的,我尝试自己定义关系,但它没有给我想要的结果。

标签: php laravel-5 categories laravel-eloquent


【解决方案1】:

如果我理解得很好,要获得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()
    );
}

我在这里工作的假设是类别名称是唯一的 - 否则您将不得不遍历记录集合。

【讨论】:

  • 你的假设是正确的!名称将是唯一的。
  • @Sebastian,我不得不从行中删除 HasMany 以获得结果。否则会导致“类型错误:App\Category::children() 的返回值必须是 App\HasMany 的实例,Illuminate\Database\Eloquent\Relations\HasMany 的实例返回”。公共函数 children(): HasMany
  • 对不起 - 是的,这应该作为use lluminate\Database\Eloquent\Relations\HasMany 导入你的班级,它会正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 2014-07-02
  • 1970-01-01
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
相关资源
最近更新 更多