【发布时间】: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 Recursive Relationships