如何在Laravel迁移和模型中创建反射关系

3
我想要一个具有“一对多”关系的表格,例如:我有一个“人员表”,其中可以包含许多其他“人员”。以下是我的代码:
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');
}

请看这张图片:

我正在尝试实现的关系

2个回答

3
Person.php 模型中:
public function parent()
{
    return $this->belongsTo('App\Person', 'parent_id');
}

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

是的,这是一个不错的...但你的一对多关系的名称让人想到“孩子”,比如“The Person has many Child”。 - Inzamam Idrees
@jochri3,请检查我的编辑答案,使用“Person”模型建立父母和子女关系。 - Inzamam Idrees
1
非常感谢。 - Christian LSANGOLA

1
在您的迁移中添加parent_id,并在您的模型中定义关系。
public function people()
   {
         return $this->belongsTo('App\Person')->withDefault();
   }

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

那么,我的“迁移”文件没问题了吗? - Christian LSANGOLA
我认为parent_id应该是可空的。 - Palak Jadav
是的,你说得对,parent_id应该是可空的。我已经修改了。谢谢。 - Christian LSANGOLA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接