簡體   English   中英

prisma findUnique 只接受一個唯一參數

[英]prisma findUnique where takes only one unique argument

我遇到了一個問題,我需要通過用戶名和 email 檢查用戶是否存在,因為兩者都是數據庫中的唯一字段,但出現錯誤。 Argument where of type UserWhereUniqueInput needs exactly one argument, but you provided username and email. Please choose one. 那么,有沒有辦法只執行一次這個查詢? 而不是像下面這樣為每個運行一個

const user = await prisma.user.findUnique({
        where: {
          username,
          email,
        },
      });

而不是這樣

const user = await prisma.user.findUnique({
        where: {
          username,
        },
      });

const user = await prisma.user.findUnique({
        where: {
          email,
        },
      });

我不完全確定,但是 prisma 返回一個 JS object...所以也許這樣的查詢應該有效:

const query = await prisma.user.findUnique({
        where: {
          user: user.username
        },
       select: {
         user: true,
         email: true
      }
      });

我相信這應該可行,但它仍然只能找到一個獨特的。 我不確定你為什么會 select 用戶 + email 都是獨一無二的,因為我假設一個無論如何都與另一個相關聯。

如果我的解決方案無法工作,我會在這里查看更多答案: https://www.prisma.io/docs/concepts/components/prisma-client/crud#findfirst

從邏輯上講,email 是一個唯一字段(不會有兩個人共享的同一個 email)。 用戶名字段不是唯一的(多個用戶同名)。
僅以下代碼就足以獲取該唯一用戶。

const user = await prisma.user.findUnique({
        where: {
          email
        },
      });

但是讓我們假設 email 或單獨的用戶名不是唯一的,並且 email 和用戶名的組合是唯一的。

修改如下所示的架構

model user {
  username : String
  email    : String
  @@unique([username, email])
}

您現在可以通過唯一的 email 和用戶名進行查詢,而無需提供多個 where arguments

   const user = await prisma.findUnique({
        where: {
          username_email : { username, email },
        },
      });

參考:

const users = await prisma.user.findMany({
       where: {
        OR: [
          {username},
          {email}
        ]
      }
  });
 if (users.length !== 0) {...}

如果您正在尋找一個可以為您帶來單一結果的獨特價值,您也可以使用 findFirst。 這會給你 Object 而不是數組。 即使您正在尋找一個唯一值,findMany 也會返回一個數組。

const users = await prisma.user.findFirst({
 where: {OR: [{username},{email}]}
});

暫無
暫無

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

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