I have chapter table. Each chapter may have multiple notes and each not is created by a user.
Table structure
users => id | name
chapters => id | title
notes => id | chapter_id | user_id
Relationship
//Chapter Model
public function notes()
{
return $this->hasMany(Note::class, 'chapter_id', 'id');
}
//Note Model
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
Now I'm trying to get all chapters and their notes and user who created the note.
Chapter::with([
'notes' => function($q) {
$q->select('id','chapter_id','note','noted_at');
},
'notes.user' => function($q) {
$q->select('id','first_name','last_name');
},
]);
I am getting the notes relation but user relation is null
in each note
I also tried following but no luck
Chapter::with([
'notes' => function($q) {
$q->select('id','chapter_id','note','noted_at');
$q->with('user:id,first_name,last_name');
},
]);
My output should resembles to following json
{
"id":2,
"title":"Sed.",
"notes":[
{
"id":82,
"chapter_id":2,
"note":"Dicta ipsam illum possimus qui non. Nihil sed ipsum et rem reprehenderit omnis aspernatur. Ut velit quo incidunt quaerat reiciendis.",
"noted_at":383,
"user":{
"id":1,
"first_name":"Fahad",
"last_name":"Shaikh"
}
}
]
}
In simple words how can I eager load nested relationship user
while constraining both notes
and user
relationship?