在 prisma 中查找与其他元素有 N+ 关系的元素
Find elements in prisma where they have N+ relations with other elements
我有一个 prisma 模式定义如下:
model User {
id Int @id @default(autoincrement())
userName string @unique
complaints Complaint[]
}
model Complaint {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId Int
priority ComplaintPriority
}
enum ComplaintPriority {
HIGH
MEDIUM
LOW
}
我需要找到所有至少有 N 次投诉且具有 HIGHT
优先级(N 变量)的所有用户,但直到现在我还没有找到方法。理想的是使用 SQL 的 having
子句,但我在 groupBy
.
的用法中找到了关于 having
的文档
有人知道怎么做吗?
据我所知,单个 Prisma 查询无法做到这一点。但是有两个查询就很容易了。你会:
- 在
complaint
table/model 上使用 groupBy
获取 userId
值,其中 HIGH
优先级投诉的计数超过特定值。
- 使用这些
userId
值在 User
table/model 中执行 findMany
。
这是它的样子
const userIdGroupBy = await prisma.complaint.groupBy({
by: ["userId"],
where: {
priority: "HIGH"
},
having: {
priority: {
_count: {
gte: _VIOLATION_THRESHOLD_
}
}
}
});
// convert array of objects to array of id values.
let userIdArray = userIdGroupBy.map(item => item.userId)
let usersWithViolations = await prisma.user.findMany({
where: {
id: {
in: userIdArray
}
}
})
我有一个 prisma 模式定义如下:
model User {
id Int @id @default(autoincrement())
userName string @unique
complaints Complaint[]
}
model Complaint {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id])
userId Int
priority ComplaintPriority
}
enum ComplaintPriority {
HIGH
MEDIUM
LOW
}
我需要找到所有至少有 N 次投诉且具有 HIGHT
优先级(N 变量)的所有用户,但直到现在我还没有找到方法。理想的是使用 SQL 的 having
子句,但我在 groupBy
.
having
的文档
有人知道怎么做吗?
据我所知,单个 Prisma 查询无法做到这一点。但是有两个查询就很容易了。你会:
- 在
complaint
table/model 上使用groupBy
获取userId
值,其中HIGH
优先级投诉的计数超过特定值。 - 使用这些
userId
值在User
table/model 中执行findMany
。
这是它的样子
const userIdGroupBy = await prisma.complaint.groupBy({
by: ["userId"],
where: {
priority: "HIGH"
},
having: {
priority: {
_count: {
gte: _VIOLATION_THRESHOLD_
}
}
}
});
// convert array of objects to array of id values.
let userIdArray = userIdGroupBy.map(item => item.userId)
let usersWithViolations = await prisma.user.findMany({
where: {
id: {
in: userIdArray
}
}
})