我想要一个表
,它本身有一个一对多
。例如:我有一个 people 表
,它可以有许多其他 people
。这就是我的代码的样子:
public function up()
{
Schema::create('people', function (Blueprint $table) {
$table->string('id')->primary();//Here my PK is a string
$table->string('name');
$table->string('title')->nullable();
$table->string('parent_id');//Here is the foreign key of another person
$table->timestamps();
});
}
在我的 Person.php 模型中我有这个:
public function people()
{
return $this->belongsTo('App\Person')->withDefault();
}
public function person()
{
return $this->hasMany('App\Person');
}
看看这张图片:
最佳答案
在 Person.php 模型中:
public function parent()
{
return $this->belongsTo('App\Person', 'parent_id');
}
public function child()
{
return $this->hasMany('App\Person', 'parent_id');
}
关于laravel - 如何在 Laravel 迁移和模型中建立自反关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55139867/