问题
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