考虑下面的节点图:
如上图所示,我想创建一个函数,可以从顶级节点告诉我关系的深度。
实例模型
/**
* Get the immediate parent instance of the instance.
*/
public function parent()
{
return $this->hasOne(Instance::class);
}
/**
* Get the children instances of the instance.
*/
public function children()
{
return $this->hasMany(Instance::class);
}
/**
* Get the depth of an instance.
* @return int
*/
public function getDepthAttribute()
{
// TODO
}
实例表
Schema::create('instances', function (Blueprint $table) {
$table->id();
$table->string('name', 32);
$table->foreignId('instance_id')->nullable();
$table->timestamps();
});
Schema::table('instances', function (Blueprint $table)
{
$table->foreign('instance_id')->references('id')->on('instances')->onUpdate('cascade')->onDelete('cascade');
});
实例表示例
id name instance_id | (getDepthAttribute() should return)
-------------------------- |
1 A NULL | 0
2 B 1 | 1
3 C 2 | 2
4 D 3 | 3
5 E 3 | 3
6 F 3 | 3
一句话,我的问题是:“如果一个实例有父实例,加1。重复直到父实例没有父实例。然后返回最终值。”
我怎样才能在 Laravel 中正确地做到这一点?