[英]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.