我有一个类别,子类别,子类别的类别都在一个表中。表看起来像这样
$table->increments('id');
$table->integer('parent_id')->nullable()->unsigned()->default(NULL);
$table->foreign('parent_id')->references('id')->on('categories')- >onDelete('cascade');
$table->string('name');
$table->timestamps();
控制器
$projects = Projects::pluck('post','parent_id');
视图
@if (count($projects) > 0)
<ul>
@foreach ($projects as $project)
@include('partials.project', $project)
@endforeach
</ul>
@endif
partials.project
<li>{{ $project['name'] }}</li>
@if (count($project['children']) > 0)
<ul>
@foreach($project['children'] as $project)
@include('partials.project', $project)
@endforeach
</ul>
@endif
我将孩子们标记在哪里,我希望他们的子类别和类别去。我该如何解决这个问题
答案 0 :(得分:2)
假设您已定义关系:
// Project.php
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
您可以将视图称为
// ProjectController.php
public function showNested()
{
$max_level = 3; // the max nesting level you will support
$eager_load = implode('.', array_map(function () { return 'children'; }, range(1, $max_level)));
$projects = Project::where('parent_id', null)->with($eager_load)->get();
return view('projects', compact('projects', 'max_level'));
}
父视图:
// projects.blade.php
<ul>
@foreach($projects as $project)
@include('partials.project', [
'project' => $project,
'level' => 1,
'max_level' => $max_level
])
@endforeach
</ul>
局部视图:
// partials/project.blade.php
<li>{{ $project->name }}</li>
@if ($level < $max_level && $project->children->count())
<ul>
@foreach($project->children as $child)
@include('partials.project', [
'project' => $child,
'level' => $level + 1,
'max_level' => $max_level
])
@endforeach
</ul>
@endif
(更新)
的解释
$eager_load = implode('.', array_map(function () { return 'children'; }, range(1, $max_level)));
你知道什么是急切加载,对吗?基本上,我想要的是从数据库预取所有嵌套项目,直到所选级别。所以,如果你做->with('children')
,它将获得项目及其直接子项。如果你->with('children.children')
,它将获得顶级项目和2个级别的孩子。
所以,打破它:
$max_level = 3;
// variable
range(1, $max_level);
// gives [1, 2, 3]
array_map(
function () { return 'children'; },
range(1, $max_level)
);
// gives ['children', 'children', 'children']
implode('.', array_map(function () { return 'children'; }, range(1, $max_level)));
// gives 'children.children.children'