外键同表laravel获取树视图

时间:2017-10-29 20:01:33

标签: php laravel loops for-loop while-loop

我正在使用Laravel 5.5项目。

我有locations表,其定义如下:

$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();

现在主键和forgen键位于同一个表中 id和位置ID 和id在位置模型中有这种关系

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

现在我需要绘制ul li树视图,以location_id为空 我做了这个

@foreach($locations->where('location_id','=','null') as $location)

@endforeach

此循环启动第一个父位置 我需要的是while循环或for循环将所有子位置嵌套在第一个foreach循环内,并将孙子嵌套在子循环中作为ul li或其他任何像这张照片 enter image description here

谢谢

1 个答案:

答案 0 :(得分:2)

这只是有点令人困惑但很容易加载第n级树。为此,我们可以创建一个递归函数来加载子或父关系。

// Location model
// loads only 1st level children
public function children()
{
   return $this->hasMany(Location::class, 'parent_id', 'id');
}

// recursive, loads all children
public function childrenRecursive()
{
   return $this->children()->with('childrenRecursive');
}

// load 1st level parent
public function parent()
{
   return $this->belongsTo(Location::class,'parent_id', 'id');
}

// recursive load all parents.
public function parentRecursive()
{
   return $this->parent()->with('parentRecursive');
}

// here is how you can load the target tree structure.
$locations = Location::with('childrenRecursive')->whereNull('parent_id')->get();


//here is how you can create your menu tree.
function createMenuTree($locations) {
    echo "<ul>";
    foreach ($locations as $location) {

        if ($location->children->isEmpty() !== false) {
            echo "<li>" . $location->name;
            menu($location->children);
            echo "</li>";
        } else {
            echo "<li>" . $location->name . "</li>";
        }
    }
    echo "</ul>";
}