添加 app/Traits/TreePath.php
parent
3e2d22a758
commit
cf9a2f18df
|
|
@ -0,0 +1,84 @@
|
|||
<?php
|
||||
|
||||
namespace App\Traits;
|
||||
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Model Tree
|
||||
*
|
||||
* parent_id: 上级id, 默认: 0
|
||||
* path: 所有上级id, 例如: -1-2-3-
|
||||
* sort: 排序(正序)
|
||||
*/
|
||||
trait TreePath
|
||||
{
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (Model $model) {
|
||||
if ($model->parent_id) {
|
||||
$parent = static::query()->findOrFail($model->parent_id);
|
||||
$model->path = $parent->path . $parent->id . '-';
|
||||
} else {
|
||||
$model->parent_id = 0;
|
||||
$model->path = '-';
|
||||
}
|
||||
});
|
||||
|
||||
static::updating(function (Model $model) {
|
||||
if ($model->parent_id) {
|
||||
$parent = static::query()->findOrFail($model->parent_id);
|
||||
$model->path = $parent->path . $parent->id . '-';
|
||||
} else {
|
||||
$model->parent_id = 0;
|
||||
$model->path = '-';
|
||||
}
|
||||
});
|
||||
|
||||
static::deleting(function (Model $model) {
|
||||
static::query()->allChildren($model->id)->delete();
|
||||
});
|
||||
}
|
||||
protected function parentIds(): Attribute
|
||||
{
|
||||
return Attribute::make(
|
||||
get: fn () => explode('-', substr($this->path, 1, -1)),
|
||||
);
|
||||
}
|
||||
|
||||
public function children()
|
||||
{
|
||||
return $this->hasMany(static::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function parent()
|
||||
{
|
||||
return $this->belongsTo(static::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function scopeAllChildren($q, $pid)
|
||||
{
|
||||
return $q->where('path', 'like', '%-'.$pid.'-%');
|
||||
}
|
||||
|
||||
public function scopeSort($q)
|
||||
{
|
||||
return $q->orderBy('parent_id')->orderBy('sort');
|
||||
}
|
||||
|
||||
public static function getTreeList($list, $pid = 0)
|
||||
{
|
||||
$tree = collect();
|
||||
foreach ($list->where('parent_id', $pid)->all() as $item) {
|
||||
$item->children = [];
|
||||
$children = $list->where('parent_id', $item->id);
|
||||
if ($children->count() > 0) {
|
||||
$item->children = static::getTreeList($list, $item->id);
|
||||
}
|
||||
$tree->push($item);
|
||||
}
|
||||
|
||||
return $tree;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue