Laravel中的递归菜单

时间:2019-05-26 19:39:33

标签: php laravel-5

我正在通过以下方式构建递归菜单:

public static function tree()
{
    return static::with(implode('.', array_fill(0, 100, 'children')))->where('parent_id', '=', '0')
        ->join('company_components', 'id', '=', 'company_components.component_id')
        ->where('company_components.company_id', '=', auth('api')->user()->with('company')->first()->company_id)
        ->orderBy('id')
        ->get();
}

我得到这样的东西:

[
  {
    "id":1,
    "parent_id":0,
    "name":"Cuentas",
    "url":"",
    "icon":"fa fa-user",
    "deleted_at":null,
    "created_at":"2019-05-26 18:57:02",
    "updated_at":"2019-05-26 18:57:02",
    "company_id":1,
    "component_id":1,
    "children":[
        {
          "id":2,
          "parent_id":1,
          "name":"Crear Cuenta",
          "url":"/account/create",
          "icon":"fa fa-circle-o",
          "deleted_at":null,
          "created_at":null,
          "updated_at":null,
          "children":[]
        }
     ]
  }
]

如何避免最后一个元素的空数组(不再有子元素)?

如果“孩子”没有更多孩子,有什么办法不创建该元素?

1 个答案:

答案 0 :(得分:1)

    $this->cleanMenu($menu);

    public function cleanMenu($tree)
    {
        foreach($tree as $t) {
            if (!$t->children->count() > 0) {
                unset($t['children']);
            } else {
                $this->cleanMenu($t->children);
            }
        }
    }

如果从模型中找到解决方案而无需再次迭代,那将是惊人的!

希望对您有帮助