首页 > 解决方案 > 在 Laravel 8 中获取所有后代

问题描述

我正在尝试获取元素的后代(元素子、孙子、孙子)ID。

例如在控制器中,我正在调用这样的函数:

$categories = Equipment::find(1);
$ids = [];
$nestable = Equipment::nestable($ids,$categories);

和可嵌套功能:

    public static function nestable($ids, $category)
    {
            if ($category->children->count() > 0) {
                foreach ($category->children as $child) {
                    array_push($ids, $child->id);
                    $child = self::nestable($ids, $child);
                }
            }

        return $ids;
    }

但是方法只返回孩子,而不是返回孙子,但在方法中转储数组时,我得到了孩子和孙子。功能有什么问题?

标签: laravelparent-child

解决方案


推荐阅读