这是我的数据结构:
型号:
Topic
hasMany
Article
Article
belongsTo
Topic
和hasMany
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可用方法的列表。
非常感谢任何帮助!
答案 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
关系,但我没有一个示例可以尝试。