我尝试使用Laravel显示嵌套列表。
class Person extends Model
{
public function father()
{
return $this->belongsTo('App\Person', 'father_id');
}
}
我可以像手动一样手动访问数据。
user = \App\Person::find(5);
$this->tree_string .= "<li>";
$this->tree_string .= "<label>".$user->name."</label>";
$user = $user->father;
$this->tree_string .= "<ul><li>";
$this->tree_string .= "<label>".$user->name."</label>";
$user = $user->father;
$this->tree_string .= "<ul><li>";
$this->tree_string .= "<label>".$user->name."</label>";
$this->tree_string .= "</li></ul>";
$this->tree_string .= "</li></ul>";
$this->tree_string .= "</li>";
但是我怎么在循环中这样做直到没有父亲。(比如foreach) 是我正确使用的方法。
答案 0 :(得分:1)
两个选项:
foreach
循环在Blade模板中迭代准备好的数据:@foreach ($users as $user)
<ul>
<li>
<label> {{ $user->name }} </label>
<li>
</ul>
@endforeach
include
标记,并在当前用户拥有父亲时递归包含部分: main-template.blade.php
:
@if ($user)
<ul>
@include('partials.users', ['user' => $user])
</ul>
@endif
partials/users.blade.php
:
<li><label>{{$user->name}}</label></li>
@if ($user->father)
<ul>
@include('partials.users', ['user' => $user->father])
</ul>
@endif
希望我的回答有所帮助!
答案 1 :(得分:0)
希望正确理解你的问题。 你想在你的刀片中预先(例如),就像这样
@foreach ($users as $user)
<p>This is user {{ $user->id }}</p>
@endforeach