2

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

enter image description here

Like for Parent comment 1 => replies_count is 2, but for its Child comment 3 => replies_count is null, it has to be 1.

Kajal Pandya
  • 75
  • 1
  • 7
  • `replies_count` not a model member (server should throw an error) ... field returned because server returns all asked fields .... success field? for query, not mutation? really? getting response for query is already a success, error is not a success – xadm Mar 25 '21 at 09:40
  • @xadm what did you just answered I don't get your point. Please explain. – Kajal Pandya Mar 25 '21 at 11:55
  • show your `Comment` type/schema in GraphQL Playground’s “Docs” - does it contain this counter field? – xadm Mar 25 '21 at 12:13
  • type Comment { id: ID! user_id: ID! parent_id: ID text: String deleted: Int created_at: DateTime updated_at: DateTime replies: [Comment] @hasMany replies_count: Int commentable: Post user: User } – Kajal Pandya Mar 25 '21 at 13:39
  • ok, field is defined in the type ... how defined? how value passed? ... I guess not using LH `@paginate` , like in this tut https://www.toptal.com/graphql/laravel-graphql-server-tutorial – xadm Mar 25 '21 at 21:37

0 Answers0