laravel 5.1中的菜单和子菜单

时间:2015-08-10 21:28:12

标签: php laravel-5 laravel-5.1

所以我在我的数据库中有一个id,id_parent,title等表。 我需要创建一个包含子列表的列表。我需要某种递归函数,但不知道如何在laravel中做到这一点..

我试过

class Goals extends Model {
  protected $table = 'goals';

  public function subgoals() {
    return $this->hasMany(SubGoals::class, 'id_category');
  }
}

class SubGoals extends Model {
  protected $table = 'goals';

  public function goals() {
    return $this->belongsTo(Goals::class, 'id_category');
  }
}

控制器:

$treeView = Goals::with(['SubGoals'])->get();

并查看:

@foreach($treeView as $category)
  <li>
    <a href="#"> {{ $category->title }} </a>
      <ul>
         @foreach($category->subgoals as $subcategory)
           <li><a href="#">{{ $subcategory->title }}</a></li>
         @endforeach
       </ul>
 </li>
@endforeach

没有得到正确的结果.. 也许有人有一个片段..

1 个答案:

答案 0 :(得分:2)

您不需要创建2个类,只需要像您的示例目标一样。

class Goal extends Model {
  protected $table = 'goals';

  public function subgoals() {
    return $this->hasMany(Goal::class, 'parent_id', 'id');
  }
}

然后在控制器中你需要&#34;查询所有父目标&#34;像这样:

$parent_goals = Goal::whereNull('parent_id')->get();

最后在视图中:

@foreach($parent_goals as $goal)
  <li>
    <a href="#"> {{ $goal->title }} </a>
      <ul>
         @foreach($goal->subgoals as $subgoal)
           <li><a href="#">{{ $subgoal->title }}</a></li>
         @endforeach
       </ul>
 </li>
@endforeach

是的。希望能帮到你。