Laravel Eloquent: How to count with nested relationship

痞子三分冷 提交于 2020-08-10 18:50:28

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/62905402/laravel-eloquent-how-to-count-with-nested-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!