[英]Prisma how to get data from relation as using 'where'?
我的用户棱镜架构用户模型有like[]
:
model User {
likes Like[]
}
并且 Like 模型已createdAt
。
model Like {
id Int @id @default(autoincrement())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
userId Int
createdAt DateTime @default(now())
@@unique([feedId, userId])
}
我想获取this month
user
链接到Like
模型的次数的数据。 所以我得到如下数据。
export default {
Query: {
seeAllLikeOrder: protectedResolver(() => {
const startOfMonth = new Date(
moment().startOf("month").format("YYYY-MM-DD hh:mm").substring(0, 10)
);
const endOfMonth = new Date(
moment().endOf("month").format("YYYY-MM-DD hh:mm").substring(0, 10)
);
return client.user.findMany({
where: {
likes: {
createdAt: {
gte: startOfMonth,
lt: endOfMonth,
},
},
},
orderBy: {
likes: {
_count: "desc",
},
},
take: 10,
});
}),
},
};
但是错误来了:
我想我不能根据错误信息使用。
where: {
likes: {
createdAt: {
gte: startOfMonth,
lt: endOfMonth,
},
},
},
但我不明白为什么。
因为 User 有 Like 模型并且 Like 有 createdAt 字段。
在这种情况下,如何获取我想要的数据?
该错误非常描述正在发生的事情: createdAt
不是LikeListRelationFilter
的有效属性,并且该类型仅具有属性every
、 some
或none
。
您的问题是查询likes
字段时的嵌套选择:
return client.user.findMany({
where: {
likes: { // This line
createdAt: {
gte: startOfMonth,
lt: endOfMonth,
},
},
},
orderBy: {
likes: {
_count: "desc",
},
},
take: 10,
});
在 Prisma 中,当您查询一个字段并根据嵌套字段的值进行过滤时,查询该嵌套数组字段的 API 将与查询prisma.like.findMany
不同。 在您的情况下,您的查询必须如下所示:
return client.user.findMany({
where: {
likes: { // This line is different
// Find any user where at least one of their likes abides by this condition.
// Replace with "every" to only search for users where ALL of their likes abide by this condition,
// or "none" to only search for users where NONE of their likes abide by this condition.
some: {
createdAt: {
gte: startOfMonth,
lt: endOfMonth,
},
}
},
},
orderBy: {
likes: {
_count: "desc",
},
},
take: 10,
});
文档: https ://www.prisma.io/docs/concepts/components/prisma-client/filtering-and-sorting
如果嵌套字段是单个项目(不是项目数组),您将使用is
或isNot
代替。 这里你有一个数组,所以你必须使用every
、 some
或none
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.