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

Not able to fetch data from multiple hasMany relations – laravel

I wanted to fetch whole data from all 4 relations: education,documents,references,skills along with the User table’s data. The following query only returns data from user table but not from any of the 4 relations although they have matching data in them. I have added its screenshot at the bottom. Can someone tell me how to fix this?

Controller

$u = User::where('id', $id)->with(['education','documents','references','skills'])->get();
dd($u);

User Model

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

public function education(){
    return $this->hasMany(StaffEducation::class,'id','user_id');
}
public function documents(){
    return $this->hasMany(StaffDocuments::class,'id','user_id');
}
public function references(){
    return $this->hasMany(StaffReferences::class,'id','user_id');
}
public function skills(){
    return $this->hasMany(StaffSkills::class,'id','user_id');
}

enter image description here

>Solution :

This is the right way

return $this->hasMany(StaffEducation::class, 'foreign_key', 'local_key');

public function education(){
    return $this->hasMany(StaffEducation::class,'user_id','id');
}

Use the same for the rest of your relations

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