Laravel / Eloquent:对包含批准评论的文章的主题进行迭代

时间:2018-04-20 06:52:56

标签: php database laravel eloquent

这是我的数据结构:

型号:

  • Topic hasMany Article
  • Article belongsTo TopichasMany Comment
  • Comment belongsTo Article
  • 此外,Topic hasManyThrough Comment(通过Article

数据库表:

  • topics:int id,字符串label
  • articles:int id,string content,int topic_id(外键)
  • comments:int id,string content,boolean approved,int article_id(外键)

现在,我想迭代所有topics articles approved comments。{/ p>

@FOREACH ($topics->where(...) as $topic)
  <div> 
    {{ $topic->label }} has {{ $topic->articles->count() }} articles with approved comments.
  </div>
  ...
@ENDFOREACH

不幸的是,我无法弄清楚如何定义where - 子句。或者它应该是when - 条款? Here是Laravel Collections可用方法的列表。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

$topics = Topic::whereHas('articles', function ($query) {
    $query->whereHas('comments', function ($query) {
        $query->where('approved', true);
    });
})->get();

@foreach ($topics as $topic)
<div>
    {{ $topic->label }} has {{ $topic->articles->count() }} articles with approved comments.
</div>
@endforeach

或者您可以以类似的方式使用hasManyThrough关系,但我没有一个示例可以尝试。