简体   繁体   中英

Prisma constraint to ensure single item in database

I have a Category model inside my prisma schema that has a field called parent :

model Category {
  id        Int      @default(autoincrement()) @id
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String @unique
  parent    Boolean
  parentId  Int?
  stores    Storefront[]
  products  Product[]
}

How can I ensure there is always at least 1 Category where the parent is true? And if not, send back an error. Do I have to do this manually inside a mutation?

Example, updateCategory mutation:

export default async function updateCategory({ where, data }: UpdateCategoryInput, ctx: Ctx) {

  const { title, parent, parentId } = CategoryInput.parse(data)


  const category = await db.category.update({
    where,
    data: {
      title,
      parent,
      parentId: parent ? null : parentId,
    },
  })

  return category
}

It seems this is business logic you would have to implement in your resolver before update, I don't think this can be achieved by setting constraints in the DB or on a Prisma-level.

Here's what I would suggest to enforce this constraint in your application:

export default async function updateCategory({ where, data }: UpdateCategoryInput, ctx: Ctx) {

  const { id, title, parent, parentId } = CategoryInput.parse(data)

  // Check how many categories there are with `parent` set to `true`
  const categories = await db.category.findMany({
    where: { parent: true }
  })
  if (categories.length === 1 && categories[0].id === id && !parent) {
    // if all these conditions are true, you are about to set the last
    // category with `parent` equals `true` to `false` which must not happen
    throw new Error(`This mutation would set the last parent to false`)
  }

  const category = await db.category.update({
    where: {
      id: id
    },
    data: {
      title,
      parent,
      parentId: parent ? null : parentId,
    },
  })
  return category
}

Note that you would have to add this check to every part in your application where parent is potentially set to false .

Let me know if that helps or if you have any further questions:)

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