Laravel Foreach ul li作为无穷大条件

Laravel Foreach ul li作为无穷大条件,laravel,loops,for-loop,Laravel,Loops,For Loop,我有下表: public function up() { Schema::create('locations', function (Blueprint $table) { $table->increments('id'); $table->string('location_name',50); $table->integer('location_id')->unsigned(); $table-&g

我有下表:

public function up()
{
    Schema::create('locations', function (Blueprint $table) {
        $table->increments('id');
        $table->string('location_name',50);
        $table->integer('location_id')->unsigned();
        $table->foreign('location_id')->references('id')->on('locations');          
        $table->softDeletes();
        $table->timestamps();
    });
}
我希望它看起来像一棵树,但仍然能够在我的ulli下拉列表中使用它。 在我的刀片里,我做到了:

                    <ol>
                        @foreach($locations->where('location_id','=',null) as $location)
                            <li draggable='true'>
                                {{$location->location_name}}
                                <ol>
                                @foreach($location->get_sub as $location_sub)
                                    <li draggable='true'>{{$location_sub->location_name}}</li>
                                @endforeach
                                </ol>
                            </li>
                        @endforeach
                    </ol>
通过这样做,我可以到达父/子位置;然而,有时我需要父母的孩子的孙子孙女等。 我的想法是做一个while循环来查找每个子位置和 并将其放入ul li列表中,每个get_sub将其显示在其下,并在父ul li中显示ul li,如下所示:


有时,虽然该位置有7个父亲,如果我知道父亲的数量,我可以在while中循环多达父亲的数量,但我不知道编译时的数量。

您的模型如何调用?让我们假设它是命名位置。将您的关系名称添加到位置模型中的$with属性:

protected $with = ['get_sub'];
在控制器中(或在执行此操作的任何位置),您可以调用:

$locations = Location::get();
您将得到嵌套列表。但是,如果你的单子长得太多,要小心。每次从db中获取一个位置时,它都会包含它的所有子对象。因此,请检查是否可以从$with数组中动态添加或删除该“get_子”项

protected $with = ['parent'];

public function parent()
{
    return $this->belongsTo('App\Location', 'location_id', 'id');
}
要从子级开始,您需要在位置模型中定义一个parent()方法,并将其添加到$with数组中

protected $with = ['parent'];

public function parent()
{
    return $this->belongsTo('App\Location', 'location_id', 'id');
}

你的模特叫什么名字?让我们假设它是命名位置。将您的关系名称添加到位置模型中的$with属性:

protected $with = ['get_sub'];
在控制器中(或在执行此操作的任何位置),您可以调用:

$locations = Location::get();
您将得到嵌套列表。但是,如果你的单子长得太多,要小心。每次从db中获取一个位置时,它都会包含它的所有子对象。因此,请检查是否可以从$with数组中动态添加或删除该“get_子”项

protected $with = ['parent'];

public function parent()
{
    return $this->belongsTo('App\Location', 'location_id', 'id');
}
要从子级开始,您需要在位置模型中定义一个parent()方法,并将其添加到$with数组中

protected $with = ['parent'];

public function parent()
{
    return $this->belongsTo('App\Location', 'location_id', 'id');
}

$locations=Location::withTrashed()->get();返回视图('locations.create',压缩('locations');这是我的控制器代码我已经按照你说的做了我的问题是我希望它从最后一个子项开始,而不是从父项$locations=Location::withTrashed()->get();返回视图('locations.create',压缩('locations');这是我的控制器代码我已经做了你说的我的问题是我希望它从最后一个孩子开始,而不是从父母开始