Home > Software engineering >  How to return a relation with a row in the same table
How to return a relation with a row in the same table

Time:11-30

My Table structure

Users table

  • id
  • parent_id

How i want the system to work

This db users table is set up for a school system that has multiple user types (student, parent and teacher)

A student has a parent_id and this field is nullable for users that arent students. The parent_id field is the id of another user in the same table

What i want to achieve

I want to be able to return an eloquent relation with the parent of a child based on the parent_id of the child

CodePudding user response:

It should not be that tricky. The relationship will returns one instance of model, which is the parent. Just play around with your table name, foreign key and so on.

public function getParent()
{
    return $this->belongsTo(Student::class, 'parent_id');
}

Similarly, you can quite do the same thing in reverse: get all "child student" of the current model instnace:

public function children()
{
    return $this->hasMany(Student::class, 'parent_id');
}
  • Related