【问题标题】:Foreign key same table laravel get tree view外键同表 laravel 获取树视图
【发布时间】:2018-04-10 19:21:48
【问题描述】:

我正在使用 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 为 null 开始 我这样做了

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

@endforeach

这个循环开始第一个父位置 我需要的是 while 循环或 for 循环将所有子位置嵌套在第一个 foreach 循环中,并将孙子嵌套在子循环中作为 ul li 或类似这张照片的任何其他内容

谢谢

【问题讨论】:

  • 向我们展示您目前拥有的代码 :)

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


【解决方案1】:

这有点令人困惑,但很容易加载相关的第 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>";
}

【讨论】:

  • (id, location_name, location_id) (1, 'المستودع الرئيسي', NULL), (2, 'مستودع فوتينا', 1), (9, 'سدةيسي , 2), (10, 'معرض الاوتوستراد', 1), (11, 'سدة شمال', 2), (12, 'رف 51', 9), (13, 'sdaasf', NULL);我需要从这个值中绘制嵌套的 ul li
  • 你可以创建一个函数并递归调用它来创建一些html并回显出来。
  • menu($location->children) 应该是 createMenuTree($location->children);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 2022-06-13
  • 2020-04-30
  • 1970-01-01
  • 2019-04-07
  • 2019-03-30
  • 1970-01-01
相关资源
最近更新 更多