Как сделать рефлексивные отношения в миграции и модели Laravel - PullRequest
1 голос
/ 13 марта 2019

Я хотел бы иметь 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 ]

2 голосов
/ 13 марта 2019

In Person.php модель:

public function parent()
{
    return $this->belongsTo('App\Person', 'parent_id');
}

public function child()
{
    return $this->hasMany('App\Person', 'parent_id');
}
1 голос
/ 13 марта 2019

Добавьте parent_id в вашу миграцию и определите отношения в вашей модели

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

   public function person()
 {
     return $this->hasMany(self::class, 'parent_id');
  }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...