最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to create a optional list field in prisma - Stack Overflow

programmeradmin5浏览0评论

I am creating a basic crud api with nodejs and prisma. My Schema is as follows:

generator client {
       provider = "prisma-client-js"
}

datasource db {
       provider          = "postgresql"
       url               = env("DATABASE_URL")
       shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

  

model Category {
       id          String    @unique @default(cuid())
       title       String
       description String
       products    Product[]
}

model Product {
  id          String    @unique @default(cuid())
  title       String
  description String
  price       Float
  createdAt   DateTime  @default(now())
  updatedAt   DateTime?

  category   Category? @relation(fields: [categoryId],  references: [id])
  categoryId String?
}

I am creating a basic crud api with nodejs and prisma. My Schema is as follows:

generator client {
       provider = "prisma-client-js"
}

datasource db {
       provider          = "postgresql"
       url               = env("DATABASE_URL")
       shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

  

model Category {
       id          String    @unique @default(cuid())
       title       String
       description String
       products    Product[]
}

model Product {
  id          String    @unique @default(cuid())
  title       String
  description String
  price       Float
  createdAt   DateTime  @default(now())
  updatedAt   DateTime?

  category   Category? @relation(fields: [categoryId],  references: [id])
  categoryId String?
}

I am trying to make the products field in the Category model optional. But Prisma doesn't allow that. But I want my users to create a category even without creating a post or vice-versa. How can I get around this?

Share Improve this question asked Jan 12, 2022 at 13:26 Asief MahirAsief Mahir 1251 gold badge2 silver badges6 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

According to the Prisma documentation, lists cannot be optional: https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#remarks-5

However, the products field not being optional does not mean that it cannot be an empty when a new Category is created:

await prisma.category.create({
  data: {
    title: 'books',
    description: 'books',
    products: {},
  }
})

Then you can create or connect the product later:

await prisma.category.update({
  where: {
    id: "category-id"
  },
  data: {
    products: {
      connect: {
        id: "product-id"
      }
    }
  }
})
发布评论

评论列表(0)

  1. 暂无评论