Hi guys,
So I am trying to build a small comment system with replies feature. Now I have create the content type for comment kind of like this:
It has a self relation of a comment has many replies(which is also a comment) and a comment has a parent comment which make the comment as reply.
Now I also added a field called count. What I am hoping to accomplish is when a comment gets a reply or someone delete their reply over a comment. The count field get updated automatically to amount of replies a comment currently has.
If anyone has any idea on this kindly help please.
Thank You
for the count you will want to take a look at the model lifecycles: https://strapi.io/documentation/v3.x/concepts/models.html#lifecycle-hooks
This will let you run some queries before or after another one, so say afterCreate you will want to check how many existing comments there are and make an update (could also do before as well).
2 Likes
Ok, I kind of got the get the idea on these lifecycle methods but I am unable to figure out the logic to setup using this. For example, this is my payload data for a comment : { name: ‘sadas’, content: ‘sadasdasd’, parent_comment: ‘1’ }. I am creating a new comment and setting the parent_comment value to 1 which basically says that this comment is the reply to comment with id 1. Now how would I update the count field on comment with id 1 in lifecycle method?
Basically you would want to run a query and search for that parent ID so something like strapi.query('comment').count({ 'parent_comment': 1 })
which would give you a count that you can pass into strapi.query('comment').update({ id: 1 }, { count: whatever })
1 Like
A many many thanks for such a short answer. I was kinda trying it with strapi.services which got a bit complicated. Thank you for your valuable answer. 
No problem, it’s best when doing some custom stuff like this to skip straight to strapi.query()
as that is what executes the database queries. Just remember that calling that .query inside of a lifecycle function especially since you have a self referencing relation could cause a race condition.
You will need to know when to “skip” or you will just cause a cascading recursion of lookups
A well place if () {}
here would be a good idea.
1 Like