Complicated groupBy query
Hey there, I am attempting to do something with Prisma that may be undoable. I am still very new to web dev and Prisma, so be aware I don't doubt I'm missing something obvious here.
I would like to use
post.findMany()
to find posts for a specific user, but in this query I would like to include the number of reactions
associated with a post for a kind of reactionType
. In my project, I am using emoji reactions on posts, and I need to return the number of reactions per emoji type (reactionType
). However, I am at a loss for how to do this without many queries per request.
Using groupBy()
works if I grab the posts first and then use the post.id
of each post...
^ This returns the following:
...and then merging the results from this with the original posts list, but this method is fairly complicated and I still haven't solved how to include a boolean value which indicates whether or not the current user has reacted to this post with a given emoji/reactionType
... this would require additional queries.
I think the ideal structure would be an object called reactionTypes
of the following type appended to the post
object:
... where the key here is the id
of the reactionType
like "U+2764
" which is the unicode for a red heart emoji. Of course, I don't exactly need this format, I just need this data 🙂 (i.e., reacted
boolean, count
number)
If anyone has thought about how I might be best include this reaction data, I would greatly appreciate it. I've been struggling for hours on this.
For schema-related details, see the below schema.prisma
(comment)Solution:Jump to solution
Hey Jon, your query worked well. I modified it return the structure I needed:
```sql
-- @param {String} $1:Post ID
-- @param {String} $2:User ID...
5 Replies
Hacked around a bit and I think this is close to what you want:
Obviously I don't have your data set so I can't confirm if that would be exactly what you want.
Thank you, @Jon Harrell! I greatly appreciate this.
let me know how it works for you. I can try and tweak things to see if I can get a better answer, but I think that will help get you in the right direction.
Solution
Hey Jon, your query worked well. I modified it return the structure I needed:
Here is the TypeScript that I used to merge the query into another posts query. This isn't procedure isn't necessary, since this could be handled with a single query, but I will deal with this later. Thanks again!