如何在Laravel迁移和模型中建立自反关系

时间:2019-03-13 10:38:27

标签: laravel laravel-5 eloquent

我想拥有一个table本身的one to many。例如:我就像一个people table,可以有许多其他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');
}

看看这张图片:

The relashionship that i'm trying to implement

2 个答案:

答案 0 :(得分:3)

Person.php 模型中:

type: opaqueresponse

答案 1 :(得分:2)

在迁移中添加parent_id并在模型中定义关系

public function people()
   {
         return $this->belongsTo('App\Person')->withDefault();
   }

   public function person()
 {
     return $this->hasMany(self::class, 'parent_id');
  }