Laravel-向第N个孩子值显示父级

时间:2019-01-22 13:39:47

标签: laravel

请考虑下表

enter image description here

我想要的结果:

A
---AA1
------AAA1
---------AAAA1
---------AAAA2
---AA2
B
---BB1
---BB2
------BBB1
C
---CC1
------CCC1
---CC2

我的问题:

我需要在此父级的刀片文件上显示第n个子级的值。这个孩子是充满活力的,可以处于任何深度。

我已经看到,这应该使用递归函数来完成。我在网上看到了一些指南,但似乎不是我所需要的。

有人可以帮我吗?

编辑:添加我的模型

class Type extends Model
{
  public function parent()
  {
    return $this->belongsTo('App\Type', 'parent_id');
  }

  public function children()
  {
    return $this->hasMany('App\Type', 'parent_id');
  }

  public function childrenRecursive()
  {
    return $this->children()->with('childrenRecursive');
  }
}

编辑2: 这是为了显示已接受答案中的(经过重构的)最终代码,希望这对以后的任何人都可以有所帮助:

public function buildCategoryTreeHtml($types)
    {
      $html = [];

      if($types->count()){
        $html[] = '<ul>';
        foreach($types as $type) {
          $html[] = sprintf(
            '<li>%s%s</li>',
            $type->name,
            $this->buildCategoryTreeHtml($type->children)
          );
        }
        $html[] = '</ul>';
      }
      return implode($html);
    }

1 个答案:

答案 0 :(得分:1)

我还没有实际测试过,但是例如,我有一种方法可以为类别树构建HTML。

public function buildCategoryTreeHtml($categories)
{
    $html = [];

    if(count($categories))
        $html = ['<ul>'];
        foreach($categories as $category) {
            $html[] = sprintf(
                '<li>%s %s</li>',
                $category->name,
                $this->buildCategoryTreeHtml($category->children); 
            );
        }
        $html = ['</ul>'];
    }

    return implode($html); 
}

您当然需要将类别传递给它。

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

$html = $this->buildCategoryTreeHtml($categories);

这将以您想要的格式输出类别。让我知道是否可行:)

相关问题