I wanted to fetch id
& courseName
from Course table, id
,name
& mob
from user
table and id
& FilePath
from files
table , for which the userId
of course table has the value of id
in user
table & fileId
of course table has the value of id
in files
table.The below code is not displaying any data from the user model,it shows null
for user
. Any help is much appreciated.
Course table
Id | courseName | userId | fileId |
---|---|---|---|
Course::with('user:id,name,mob','files:id,FilePath')
->select ('id','courseName')
->get();
Course Model
public function files(){
return $this->belongsTo(Uploads::class,'fileId','id');
}
public function user(){
return $this->belongsTo(User::class,'userId','id');
}
CodePudding user response:
You have confused the ownerKey and foreignKey of the user
relation. Try updating the relation to this
public function user(){
return $this->belongsTo(User::class, 'userId', 'id');
}
CodePudding user response:
let me explain how elquent runs "with"
- first in make query to get all the courses you need
- second make another query for each relation you need in with to get it and add it on it's place
for that you need to select the columns of this relation if the course belongs to a user you have to load userId to load the user data same as fileId
on that your problem will solved if you load userId and fileId like that
Course::with('user:id,name,mob','files:id,FilePath')->get();
CodePudding user response:
Try this and let me know if its working or not
Course::with([
'user' => function($q)
{
$q->select('id', 'name' , 'mob');
},
'files' => function($q)
{
$q->select('id', 'filePath');
}
])->get(['id','courseName']);