Hi all, trying to figure out the best way to updat...
# prisma-client
t
Hi all, trying to figure out the best way to update a single record or create it if it doesn’t exist. My schema is….
Copy code
model App {
  id                  String               @id @default(cuid())
  createdAt           DateTime             @default(now())
  updatedAt           DateTime?            @updatedAt
  name                String

  redirects Redirects[]

  @@index([slug], map: "App.slug_index")
}

model Redirects {
  id String @id @default(cuid())

  global Boolean

  afterSignup   String?
  afterLogin    String?
  afterLogout   String?

  appId String
  app   App    @relation(fields: [appId], references: [id])
}
I want to update a single record that matches an
appId
and where
global
is
true
If a record doesn’t match that, I would like it to be created. Having difficulties doing that tho, since the
upsert
method only accepts the
id
field in the
where
argument. So what’s the best way to do this? The following code is essentially what I’m trying to do.
Copy code
prisma.redirects.upsert({
      where: {
        appId,
        global:true
      },
      create: {
        ...redirects,
        app: { connect: { id: appId } },
      },
      update: {
        ...redirects,
        app: { connect: { id: appId } },
      }
    })
Thanks!
m
Won't be possible in one query. More like:
Copy code
const redirect = await prisma.redirects.findFirst({ where: {appId, global: true });

   await prisma.redirects.upsert({
      where: {
        id: redirect.id
      },
      create: {
        ...redirects,
        app: { connect: { id: appId } },
      },
      update: {
        ...redirects,
        app: { connect: { id: appId } },
      }
    })
Or you could try making a composite id from appId and global: https://www.prisma.io/docs/concepts/components/prisma-schema/data-model#composite-ids
t
ah gotcha. Thanks for the reply! I’ll go with the 2 methods.