Hello Guest! Welcome to my website.

You can benefit from our privileges as a member of our site.

or Register

Question Unable to get data on joining Multiple Eloquent Relationships

admk

Member
Joined
Oct 10, 2021
Messages
46
Reaction score
2
Points
8
i wanted to display id,FileName & FilePath from Files table and id & name from User table along with the course table columns - id,courseDisplayName & aboutCourse. But it is returning null from both files & user relations.How can i fix this?
$course=Course::with(['files:id,FileName,FilePath','user:id,name'])
->select('id','courseDisplayName','aboutCourse')
->where('userId',$request->tutorId)
->get();

Course Model
PHP:
public function files()
{
return $this->belongsTo(Files::class, 'fileId', 'id');
}

public function user()
{
return $this->belongsTo(User::class, 'userId', 'id');
}

This gives an output as below:
PHP:
[
{
"id": 20,
"courseDisplayName": "asasasb",
"aboutCourse": null,
"files": null,
"user": null
},
{
"id": 14,
"courseDisplayName": "yuu",
"aboutCourse": "kljkl",
"files": null,
"user": null
}
]
 

max

New member
Joined
Oct 21, 2021
Messages
17
Reaction score
0
Points
1
You will have to select the foreign keys fileId and userId too in order to use the relationship of files and user so the query will be like

PHP:
$course=Course::with(['files:id,FileName,FilePath','user:id,name'])
->select('id','courseDisplayName','aboutCourse', 'userId', 'fileId')
->where('userId',$request->tutorId)
->get();
 
Top