douhuan1257 2018-04-20 06:52
浏览 58
已采纳

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

This is my data structure:

Models:

  • Topic hasMany Article
  • Article belongsTo Topic and hasMany Comment
  • Comment belongsTo Article
  • Additionally, 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!

  • 写回答

1条回答 默认 最新

  • doubiao9775 2018-04-20 07:38
    关注
    $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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?