[Subquery] Select from one table based on select (array) from another table
See original GitHub issueProblem
In my project there’s often such a case when you need to select items from one table based on select from multiple tables (get array of ids or tags). And the select logic can be quite complicated (for instance I need to select array of tags associated with an author and based on that (those tags) select posts). I’ve read the documentation and wasn’t able to find appropriate solution. Developing those queries is quite frustrating, so it would be nice to have a typed abstraction above it. Right now I’m using the raw queries, but title aliases are not working with that (and I have to write my own alias methods to turn entity.my_property into entity.myProperty).
Suggested solution
maybe something like that
const resultPosts = await prisma.post.findMany({
where: {
inArray: [
{
selectFrom: [
select: {tag},
from: prisma.authorSubscriptions,
where: { author: uuid }
];
},
{
selectFrom: [
select: {tag},
from: prisma.postTags,
where: { id: postId }
]
}
]
},
})
Alternatives
But I don’t insist on the syntax above, probably there’re better solutions…
Issue Analytics
- State:
- Created 2 years ago
- Reactions:16
- Comments:6 (2 by maintainers)
Top GitHub Comments
This is a pretty common use-case for me. Today I was Googling to try to figure out how Prisma does subselects (without using raw queries) and I was surprised to learn that it doesn’t support this yet. I’m a little concerned that you’d ask why a user couldn’t just execute multiple queries. Any use-case in which you have to execute multiple queries when you can execute a single query is obviously non-optimal. I’m sure I’m not the first person to say this, but subselects (more generically subqueries) is something that ActiveRecord has supported since forever.
(^ simplified for clarity) I have three tables: one for posts, one for posttagmap (tags associated with one post) and one for subscriptions by tags (not one tag but many tags, it’s important). I need 1) get subscriptions (array of tags) by author (uuid) 2) get posts by subscriptions (array of tags, associated with one author), acquired from step 1.
Right now I can do it in two steps
But, as I know, making two queries instead of one is quite expensive, isn’t it? (although if there’s an alternative, I would be glad to find it out).