如何使用laravel计算hasMany关系的用户特定注释

时间:2018-05-27 04:48:42

标签: php laravel orm

如何计算这个场景中特定用户的评论,一个用户有多本书,一本书有多章,章节属于一本书,章节有很多评论和评论属于一章?

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

    public function comments()
{
    return $this->hasManyThrough(
               'App\comments', 'App\Chapter','id','chapter_id'
    );
}

这是我的循环

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

1 个答案:

答案 0 :(得分:1)

你需要两种关系。将其添加到您的User模型中:

public function chapters()
{
    return $this->hasManyThrough(Chapter::class, Book::class);
}

这是Chapter

public function comments()
{
    return $this->hasMany(Comment::class);
}

然后你可以计算这样的评论:

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