Laravel Eloquent:如何使用嵌套关系进行计数 [英] Laravel Eloquent: How to count with nested relationship

查看:45
本文介绍了Laravel Eloquent:如何使用嵌套关系进行计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有四个表:标签,帖子,回复和post_tag

Let's say we have four tables: tags, posts, replies, and post_tag

tags table:

id  tag
1   tag A
2   tag B
3   tag C    

posts table:

id  post_content
1   some text A
2   some text B
3   some text C

post_tag table: (for many-many relationship between posts and tags)

post_id  tag_id
1        1
1        2
2        3

replies table:

id  post_id
1   1
2   1
3   2    

现在,我希望生成一个表格,该表格可以为我提供每个标签的总回复数.基于上述表格的示例输出为:

Now I wish to generate a table which gives me the total replies count for each of the tag. A sample output based on the above tables would be:

id  tag_id  replies_count
1   1       2
2   2       2
3   3       1

我已经在标签和帖子之间建立了关系,但是我有什么办法可以在标签上生成一种关系,从而使我对标签的所有答复都可以?像

I already have a relationship between tag and posts, but is there any way for me to generate a relationship on tags that would give me all the replies for a tag? Something like

function replies() {
   return $this->posts()->replies()
}

最后但并非最不重要的一点是,我希望进一步:最终的表格是一个包含每个标签的发帖数和回复数的表格

Last but not least, I would wish to get one step further beyond this: the final table I wish to get would be a table with both post count and replies count for each of the tags

id  tag_id  posts_count  replies_count
1   1       1             2
2   2       1             2 
3   3       1             1

推荐答案

除了在您的 Tag 模型中创建新的关系方法外,您还可以附加回复"使用 $ with 属性自动与您的 Post 模型建立关系.每当您获取与该标签相关的所有帖子时,它还将包括与该帖子相关的所有回复.

Instead of creating a new relationship method in your Tag model, you could attach a "replies" relationship automatically to your Post model using $with attribute. Whenever you fetch all the posts related to that tags, it will include all the replies related to that post as well.

我不建议您创建一个表来仅统计标签的答复,您可以在客户端通过利用响应数据来做到这一点.

I would not recommend creating a table just to count the replies of a tag, you can do that on the client side by utilizing the response data.

这篇关于Laravel Eloquent:如何使用嵌套关系进行计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆