简体   繁体   中英

Prisma Client update single record in one table where value in related table = true (Not creating related records)

I am using next-auth, next.js, and prisma.

I want to update the User table, but only if the session token matches what is stored in the database. Prisma's documentation on CRUD (Related records) only provides examples how to create related records (Creating a user and posts at the same time). I only want to update a user if the session id is a match.

I would like to be able to do something like this, where the user is only updated if email + session id both match:

export default async (req: NextApiRequest, res: NextApiResponse<User>) => {
  let email = req.query.email as string;
  let sessionId = req.query.email as string;
  let username = req.query.username as string;
  let zipcodeId = req.query.zipcodeId as string;

  const updatedUser = await prisma.user.update({
    where: { email: email, sessionId: sessionId },
    data: {
      username: username,
      zipcodeId: Number(zipcodeId),
    },
  });
  res.status(200).json(updatedUser);
};
// schema.prisma
model Session {
  id           String   @id @default(cuid())
  sessionToken String   @unique @map("session_token")
  userId       Int      @map("user_id")
  user         User     @relation(fields: [userId], references: [id], onDelete: Cascade)
  expires      DateTime
  
}

model User {
  id            Int    @id @default(autoincrement())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  username     String?   @unique
  accounts      Account[]
  sessions      Session[]
  votes         Vote[]
  zipcodeId     Int?      @map("zipcode_id")
  zipcode       Zipcode?  @relation(fields: [zipcodeId], references: [id], onDelete: Cascade)
}

You would need to use updateMany in this scenario as the fields which have @unique attribute can only be passed in where clause of update query.

Here's the query through which you could add condition of email and sessionId

  const updatedUser = await prisma.user.updateMany({
    where: {
      email: 'email@email.com',
      sessions: {
        every: {
          id: '1',
        },
      },
    },
    data: {
      username: 'username',
    },
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM