aminsamadzadeh / vispobish
eloquent 模型的树结构
v1.02
2021-01-26 21:22 UTC
Requires
- laravel/framework: ^7.0
Requires (Dev)
- orchestra/testbench: ^5.3
This package is auto-updated.
Last update: 2024-09-30 01:06:23 UTC
README
将树结构添加到 Eloquent 模型。在这个包中尝试优化查询。
安装
只需运行以下命令
composer require aminsamadzadeh/simorgh
用法
创建迁移。
... public function up() { Schema::table('categories', function (Blueprint $table) { // vispobish pckage $table->string('path')->nullable(); // save path of tree $table->unsignedInteger('parent_id')->nullable(); $table->foreign('parent_id')->references('id')->on('categories'); }); } ...
将 Treeable
特性添加到模型。
... use Illuminate\Database\Eloquent\Model; use AminSamadzadeh\Vispobish\Treeable; class Category extends Model { use Treeable; } ...
命名路径
如果您想使用特殊名称保存路径,您可以在模型中添加 public $namedPathWith
属性,并在迁移中添加 named_path
。
... public function up() { Schema::table('categories', function (Blueprint $table) { $table->string('named_path')->unique(); // just used when set $pahtNamedWith }); } ...
... class Category extends Model { use Treeable; public $namedPathWith = 'name'; } ...
关系
$cat->parent()
获取父节点$cat->children()
获取子节点$cat->descendants()
获取子子节点的平坦化子节点$cat->ancestors()
获取所有父节点的平坦化列表