naneri
naneri

Reputation: 3971

How to recursively get records in Laravel?

I have entity called posts in my app. Posts can be children of other posts, so that parent post has hasMany('posts') and children have hasOne('post') the inclusion is infinite.

Here is the schema:

enter image description here

How can I recursively get all children and children of children and etc. of the first Post that has 'post_id' set to null?

Please don't comment about performance here, I do know that such a schema is bad, what I want to know is only how to correctly write the recursive function to retrieve the infinite nested posts.

For instance lets say, I have the first post 1.
Post 2 and 3 are children of post 1.
Post 4 and 5 are children of post 2.
Post 6 and 7 are children of post 3.
Post 8,9,10 are children of post 5.
Post 11,12,13 are children of post 7.
Post 14 is children of post 10.
I want to write a recursive function that will get me posts 2-14. enter image description here

Upvotes: 0

Views: 1229

Answers (1)

Nicklas Kevin Frank
Nicklas Kevin Frank

Reputation: 6337

Since you specifically asked us not to comment about performance you should just add a with attribute on the post model to include all children eagerly.

class Post extends Model
{

   protected $with = [
        'posts'
   ];

   public function posts() {
        return $this->hasMany(Post::class);
    }

}

Upvotes: 1

Related Questions