Stefan Skorpen
Stefan Skorpen's blog

Stefan Skorpen's blog

Conditional Connect in Prisma

Photo by Michael Dziedzic on Unsplash

Conditional Connect in Prisma

Stefan Skorpen's photo
Stefan Skorpen
·Oct 11, 2022·

2 min read

I want to create a product with Prisma ORM, and this product has multiple connections in my database:

Schema:

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

  published DateTime?
  creatorId String

  userId Int
  user   UserInfo @relation("products", fields: [userId], references: [id], onDelete: Cascade)

  imageId String?       @unique
  image   ProductImage? @relation("productImage", fields: [imageId], references: [id])

  affiliateId String?
  affiliate   Affiliate? @relation("productAffiliate", fields: [affiliateId], references: [id])

  brandId String?
  brand   Brand?  @relation("productBrand", fields: [brandId], references: [id])

  post  Post[]
  tagId String?
  tag   ProductTag? @relation("mainProductTag", fields: [tagId], references: [id])

  tags  ProductTag[]  @relation("productTags")
  lists ProductList[] @relation("productList")

  title       String?
  slug        String  @default("")
  description String?
  url         String?
  favorite    Boolean @default(false)
  sort        Int     @default(10)
  discount    Int     @default(0)

  price  Float   @default(0)
  valuta String?

  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
  deletedAt DateTime?
}

When I create a product I may or may not have all the connected data, like brand, affiliate, tag and so on.

To do this we can leverage the undefined variable like this: (link to Prisma documentation)

let product = await prisma.product.create({
      data: {
        title,
        description,
        url,
        creatorId: session.user.id,
        published: published ? new Date() : undefined,
        favorite: favorite ? true : false,
        user: {
          connect: {
            id: Number(session.user.userInfo),
          },
        },
        image: {
          connect: {
            id: image,
          },
        },
        affiliate: affiliate
          ? {
              connect: {
                id: affiliate,
              },
            }
          : undefined,
        brand: brand
          ? {
              connect: {
                id: brand,
              },
            }
          : undefined,
        tag: tag
          ? {
              connect: {
                id: tag,
              },
            }
          : undefined,
        post: post
          ? {
              connect: {
                id: post,
              },
            }
          : undefined,
      },
    });

For affiliate: If the affiliate variable is truthy, we do the connect, else we give the 'undefined' value.

 
Share this