I have two models Post and Comment
Post modal :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'user_id','community_id','topic_id','title','description','slug','url', 'image_url', 'timezone', 'image', 'news_organization_id'];
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
}
public function allComments()
{
return $this->hasMany('App\Models\Comment', 'commentable_id');
}
}
Comment modal :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = ['user_id', 'parent_id', 'text', 'commentable_id', 'commentable_type'];
public function user()
{
return $this->belongsTo(User::class);
}
public function commentable()
{
return $this->morphTo();
}
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
I want to fetch all comments of post with nested comments and their count in graphql query.
I have tried with the below query, it gives me a count of comments and nested comments but the count is null for nested comments. Also, there is pagination in my project.
$comments = Comment::withCount('replies')->where('commentable_id', $post->id)->where('parent_id', null)->orderBy('created_at', 'desc')->paginate($limit, ['*'], 'page', $current_page);
$last_page = $comments->lastPage();
You can see the result in the below image
Like for Parent comment 1 => replies_count is 2, but for its Child comment 3 => replies_count is null, it has to be 1.