【问题标题】:Pulling all categories and grouping them by parent id拉出所有类别并按父 ID 分组
【发布时间】:2019-09-06 07:36:19
【问题描述】:

我正在使用 Laravel 数据查询,我需要一个查询,以便在我获取类别时对父级的所有子级进行分组。

categories 表有一个 name 和一个 parent_id,categories 的路由将 parent_id 设置为 null,查询应该返回按 parent id 分组的每个类别,并且 parent 应该是每个组的第一个节点。

【问题讨论】:

标签: php laravel eloquent laravel-5.8 eloquent-relationship


【解决方案1】:

当您从查询中获取返回的集合时,您可以使用->groupBy() 方法,在该方法中您可以指定对结果进行分组的字段。

假设您的类别模型是Category

$categories = Category::all()->groupBy('parent_id')->toArray();

【讨论】:

  • 这不会返回嵌套集合。它将没有父级的所有类别分组,然后将所有具有 parent_id 1 的类别分组,等等。OP:should return every category grouped by parent id and the parent should be the first node of every group
【解决方案2】:

如果您只想在某处将类别显示为父子项,则不需要像那样收集它们,您可以在模型中建立关系,例如

class Category {
    public function children()
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function parent()
    {
        return $this->hasMany(self::class, 'id', 'parent_id');
    }
}

根据您的要求,可能是一对多而不是多对多。

现在你可以让所有的父母都喜欢

Category::whereNull('parent_id')->get();

或使用范围

Category::parent()->get(); 并在模型中定义作用域

并像这样循环遍历父类别

@foreach ( $categories as $category ) 
       {{ $category->name }}
       @foreach ( $category->children as $subCategory )
           {{ $subCategory->name }}
       @endforeach
@endofreach

并检索父母与孩子,你可以使用

Category::whereNull('parent_id')->with('children')->get();

Category::parent()->with('children')->get();

我没有测试过代码,但大致会是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多