1 year ago

get deep nested relationship, with many levels

Posted 1 year ago by mhery

i am creating an system that can have comments, and for this i created a Comment class, with these attributes:

protected $fillable = [ 'discussion_id', 'author_id', 'text', 'target_type', 'target_id', ];

and for nested comment i am using these functions:

public function parent()
    return $this->belongsTo('App\Comment', 'parent_id');

public function replies()
    return $this->hasMany('App\Comment', 'parent_id', 'id');

where i am having trouble is to get these nested comments. i found out that i can get the comment and the first level of nested comments with this query:

Comment::where('_id', $comment_id)->with('replies')->get();

but i just get the first level. if i want two levels, i have to do this:

Comment::where('_id', $comment_id)->with('replies.replies')->get();

but i dont know how many comments a comment will have. how can i get all of them without adding a new '.replies' on my query?

Please sign in or create an account to participate in this conversation.