laravel 提取所有类别并按父ID分组

knsnq2tg  于 2023-01-06  发布在  其他
关注(0)|答案(3)|浏览(141)

我与Laravel数据查询工作,我需要一个查询,这是要分组的所有孩子的父母时,我采取的类别。
categories表具有名称和parent_id,categories的路由具有设置为空的parent_id,查询应当返回由父id分组的每个类别,并且父应当是每个组的第一节点。

z3yyvxxp

z3yyvxxp1#

如果您只想将类别显示为某个位置的父子类别,则不需要像这样收集它们,您可以在模型中建立如下关系

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

我还没有测试代码,但大致上是这样的。

vnzz0bqm

vnzz0bqm2#

控制器

$locations   = OurLocation::groupBy('country_id')->with('children')->get();

模型

public function children()
    {
        return $this->hasMany(OurLocation::class, 'country_id','country_id');
    }

叶片

@foreach($locations as $index=>$location)
  @foreach($location->children as $children)
        {{ $children->company_name }} <br>
  @endforeach
@endforeach
avwztpqn

avwztpqn3#

当您从查询中获得返回的集合时,您可以使用-〉groupBy()方法,在该方法中,您可以指定结果分组所依据的字段。
假设你的分类模型是Category

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

相关问题