1
class Nested extends Model{
  public function nestedfunc()
{
    return $this->hasMany(Nested::class, 'parent_id');
}
 public function childnestedfunc()
{
    return $this->hasMany(Nested::class, 'parent_id')->with('nestedfunc');
}
}

//this is my model function for reccursion. how to add pagination to the root of the nested comments. i am storing all comments to the same table

  1. root comment 1 -nested comments of root 1 ....
  2. root comment 2 - nested comments of root 2 ....
  3. paginate the root comments
  4. root comments 3 - nested comments of root 3 ....
  5. root comments 4 -nested commets of root 4.....
  6. paginate the root comments
  7. so on
alina
  • 13
  • 2

1 Answers1

2

You don't need two separate functions here, relationships can recursively call themselves so first changes your relationships to this

public function children()
{
    return $this->hasMany(Nested::class, 'parent_id')->with('children');
}

Then for your query you can just do

Nested::where('parent_id', null)->with('children')->paginate();

When I built a nested comments model I also added a scope to make it a little more readable

public function scopeTopLevel($query)
{
   return $query->where('parent_id', null);
}

So now the call in my controller is just

Comment::topLevel()->with('children')->paginate()
Alec Joy
  • 1,848
  • 8
  • 17