I have the following 3 tables:
- Posts
- Comments
- Tags
Posts:
class Post extends Eloquent
{
public function comments()
{
return $this->hasMany(Comment::class,'post_id','id');
}
}
** Post data **
{
'id' : 1,
'title' : 'bla bla',
'created_at: 'some date'
}
Comments:
class Comment extends Eloquent
{
public function comments()
{
return $this->belongsTo(Post::class,'id');
}
public function tags()
{
return $this->hasMany(Tag::class,'id','tags_ids');
}
}
** Comments data **
{
'id' : 322,
'active' : true
'post_id' : 1,
'created_at: 'some date',
'tags_ids' : [1,2,3]
}
Tags:
class Tag extends Eloquent
{
public function tags()
{
return $this->belongsTo(Comment::class,'tags_ids');
}
}
** Tags data **
{
{'id' : 1,
'description' : 'some description1'
},
{'id' : 2,
'description' : 'some description2'
},
{'id' : 3,
'description' : 'some description3'
}
}
Post table has many comments and comments table has many tags associated with it.
How do i get all this tables together using eager loading?
Something like :
$post = Post::where('id',1)->with(['comments' => function($q) {
$q->with('tags');
}])->first();
but this query always returning empty response in the tags relationship.
What am i doing wrong?
The desired result is something like this:
{
'id' : 1,
'title' : 'bla bla',
'created_at: 'some date',
'comments':[{
'id' : 322,
'active' : true
'post_id' : 1,
'created_at: 'some date',
'tags_ids' : [1,2,3],
'tags' : [
{'id' : 1,'description' : 'some description1'},
{'id' : 2, 'description' : 'some description2'},
{'id' : 3,'description' : 'some description3'}
],
}
]
}
You can see that post contains comments inside it and comments contains tags relationship inside it as well.
P.S. I am using the 'jenssegers/laravel-mongodb' package in my project and i am trying to do it without any raw expression.
Thanks.