Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a reflexive relationship in Laravel migration and model

I would like to have a table that has a one to many with itself. Eg: I have like a people table that can have many other people.This is how my code looks like:

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();
    });
}

And in my Person.php model I have this:

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

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

Take a look to this image:

The relashionship that i'm trying to implement

like image 821
Christian Lisangola Avatar asked Sep 03 '25 05:09

Christian Lisangola


1 Answers

In Person.php model:

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

public function child()
{
    return $this->hasMany('App\Person', 'parent_id');
}
like image 168
Inzamam Idrees Avatar answered Sep 05 '25 01:09

Inzamam Idrees