Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to return a relation with a row in the same table

My Table structure

Users table

  • id
  • parent_id

How i want the system to work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading