![](/img/trans.png)
[英]How do I perform a count on a relation with a where clause in prisma?
[英]Prisma - How to use count as a where condition with relation
我将nestjs
和postgresql
与prisma
一起使用。 我有 2 个相关的表,如果第二个表中的记录数小于 - 比方说 - 3,我想创建一个 where 子句以获取记录。更多细节;
这是我的架构
model User {
id String @id
someOtherFields String
outgoingPlayMateRequest PlayMateRequest[] @relation("userId")
incomingPlayMateRequest PlayMateRequest[] @relation("targetId")
}
model PlayMateRequest {
id Int @id
requestingUser User @relation(name: "userId", fields: [requestingUserId], references: [id], onDelete: Cascade)
targetUser User @relation(name: "targetId", fields: [targetUserId], references: [id], onDelete: Cascade)
requestingUserId String
targetUserId String
someOtherFields String
response String //accept-reject-block
}
这是我的带有 where 子句的代码(我通过删除不相关的部分来简化它)
const userId = 'testUser';
return await this.prismaService.user.findMany({
where: {
NOT: {
id: userId //don't fetch user him/herself
},
lang: 'EN',
}
});
我想在这里用英文添加的条件是;
不要 select 用户与incomingPlayMateRequest 关系,如果PlayMateRequest 表中有3 条记录
response = reject
和requestingUser = userId
但是我无论如何都找不到使用count
作为 where 的条件。 如我所见,我只能获得关系计数。 我怎么能用prisma
做到这一点?
在 Prisma 中没有直接的方法来执行这样的条件,但是您可以使用以下解决方法:
groupBy
查询。map
创建与过滤条件匹配的所有用户 id 的User.id
字段数组。findMany
查询,但在过滤后的用户 ID 数组中添加一个额外的notIn
条件。这是整个事情的样子:
const userId = 'testUser';
// step 1
const dataForFilter = await prisma.playMateRequest.groupBy({
by: ['targetUserId'],
where: {
response: "reject",
requestingUserId: userId
},
having: {
targetUserId: {
_count: {
equals: 3
}
}
}
})
// step 2
let exclude_users = [userId]
exclude_users = exclude_users.concat(dataForFilter.map(item => item.targetUserId))
let result = await prisma.playMateRequest.user.findMany({
where: {
id: {
notIn: exclude_users
},
lang: "en"
}
});
我可能误解了您想要实现的查询的确切细节,但我认为这应该为您提供一般的查询结构。 根据需要调整groupBy
查询以匹配您的确切条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.