我有两个模型发布和评论
后模态:
<?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');
}
}
评论模式:
<?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');
}
}
我想获取带有嵌套评论的帖子的所有评论及其在 graphql 查询中的计数。
我已尝试使用以下查询,它为我提供了评论和嵌套评论的计数,但嵌套评论的计数为空。另外,我的项目中有分页。
$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();
您可以在下图中看到结果
就像父评论 1 => replies_count 是 2一样,但是对于它的子评论 3 => replies_count 是空的,它必须是 1。