【问题标题】:Create an array with nests using category.parent_id使用 category.parent_id 创建一个带有嵌套的数组
【发布时间】:2021-08-16 01:29:16
【问题描述】:

我为数据库中的类别创建了一个表。

parent_id(如果 root = null) 姓名 说明

我已经为 Category 模型创建了函数:

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

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

    // recursive, loads all descendants
    public function childrenRecursive()
    {
        return $this->children()->with('childrenRecursive');
    }

我需要创建一个递归函数,该函数将返回一个包含这些类别(id 和名称)树的数组(不是集合)。

我无法处理这个问题。我可以请你帮忙吗?

我通过询问返回集合:

$categories = Category::with('childrenRecursive')->whereNull('parent_id')->get();

【问题讨论】:

标签: laravel nested


【解决方案1】:

在您的 Category 模型上创建一个辅助方法。利用高阶函数,您的控制器中应该有一个单行。

public function toSimpleArray() {
   $arr =[
       'id' => $this->id,
       'name' => $this->name,
   ];

   if ($this->childrenRecursive->count() > 0) {
       $arr['children'] = $this->childrenRecursive->map->toSimpleArray()->all();
   }

   return $arr;
}

您现在可以在您的$categories 收藏中执行此操作。这将是您想要的数组表示。我个人总是会选择物品和收藏品。

$categories->map->toSimpleArray()->all();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2020-05-25
    • 2013-10-24
    • 2020-05-03
    • 1970-01-01
    相关资源
    最近更新 更多