This is my data structure:
Models:
Topic
hasMany
Article
Article
belongsTo
Topic
and hasMany
Comment
Comment
belongsTo
Article
Topic
hasManyThrough
Comment
(via Article
)DB tables:
topics
: int id
, string label
articles
: int id
, string content
, int topic_id
(foreign key)comments
: int id
, string content
, boolean approved
, int article_id
(foreign key)Now, I want to iterate over all topics
that have articles
with approved
comments
.
@FOREACH ($topics->where(...) as $topic)
<div>
{{ $topic->label }} has {{ $topic->articles->count() }} articles with approved comments.
</div>
...
@ENDFOREACH
Unfortunately, I can't figure out how to define the where
-clause. Or should it be a when
-clause? Here is a list of the methods available for Laravel Collections.
Any help is greatly appreciated!
$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
Alternatively you could use your hasManyThrough
relation in a similar way, but I don't have an example to try it out.