簡體   English   中英

Prisma 如何使用“where”從關系中獲取數據?

[英]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的有效屬性,並且該類型僅具有屬性everysomenone

您的問題是查詢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

如果嵌套字段是單個項目(不是項目數組),您將使用isisNot代替。 這里你有一個數組,所以你必須使用everysomenone

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM