Php 如何使用laravel计算hasMany关系上用户特定的评论

Php 如何使用laravel计算hasMany关系上用户特定的评论,php,laravel,orm,Php,Laravel,Orm,在这种情况下,如何计算特定用户的评论?一个用户有很多书,一本书有很多章节,章节属于一本书,章节属于一章,章节有很多评论和评论属于一章 到目前为止,这是我所做的,但我不确定这是否正确,因为我通过laravel文档中的示例所做的 public function comments() { return $this->hasManyThrough( 'App\comments', 'App\Chapter','id','chapter_id'

在这种情况下,如何计算特定用户的评论?一个用户有很多书,一本书有很多章节,章节属于一本书,章节属于一章,章节有很多评论和评论属于一章

到目前为止,这是我所做的,但我不确定这是否正确,因为我通过laravel文档中的示例所做的

    public function comments()
{
    return $this->hasManyThrough(
               'App\comments', 'App\Chapter','id','chapter_id'
    );
}
这是我的循环

@foreach($user_comments as $comment) {{$comment->comments->count()}} @endforeach

你需要两种关系。将此添加到您的
用户
型号:

public function chapters()
{
    return $this->hasManyThrough(Chapter::class, Book::class);
}
这是到
章节的

public function comments()
{
    return $this->hasMany(Comment::class);
}
然后你可以这样计算评论:

$user->load('chapters.comments');
$count = $user->chapters->pluck('comments')->collapse()->count();

我应该把代码放在哪里?在视图或控制器中$用户->加载('chapters.comments')$count=$user->chapters->pull('comments')->collapse()->count();在控制器中或作为
用户
模型中的访问者(例如
getCommentsCountAttribute()
)。然后您可以在视图中使用
{{{$user->commentscont}}
。不幸的是,我在
getCommentScontAttribute()中收到了对null
@foreach($user_comments as$user){{{$user->commentscont}}@endforeach
上的成员函数load()的错误调用
你必须用
$this
替换
$user
。运气不好,兄弟!我一直在尝试但什么都没有,我一直在得到这个错误,试图获取非对象的属性'commentsCount',这是我的用户模型公共函数getCommentsCountAttribute(){$this->load('chapters.comments');$count=$this->chapters->Pull('comments')->collapse()->count();}这就是我通过('author_comments',Auth::user())传递给视图->的内容;这是我在@foreach($author_comments as$author){{{$author->commentscont}}@endforeach视图中的foreach循环