laravel 自身无限级

暂无标签

需要依靠字段parent_id

模型User

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

public function childrenUsers()
{
    return $this->hasMany(User::class, 'id')->with('users');
}

控制器

public function index()
{
    $users = User::whereNull('parent_id')->with('childrenUsers')->get();
    return view('user.index', compact('users'));
}

父模板

<ul>
@foreach ($users as $user)
    @foreach ($user->childrenUsers as $childUser)
    @include('user.tree-item', ['child_user' => $childUser])
    @endforeach
@endforeach
</ul>

子模板

<li>
    @if (count($child_user->users)) <span>[-]</span> @endif<a href="{{ route('user', ['name'=>$child_user->name]) }}">{{ $child_user->name }}</a>
    @if (count($child_user->users))
    <ul>
        @foreach ($child_user->users as $childUser)
        @include('user.tree-item', ['child_user' => $childUser])
        @endforeach
    </ul>
    @endif
</li>