Prisma automatically creates related rows when the parent is created
P粉211600174
P粉211600174 2023-08-26 19:19:48
0
2
368

I have a pattern similar to this

model User { id Int @default(autoincrement()) settingsSettings } model Settings { userId Int settingOne Boolean @default(false) user User @relation(fields: [userId], references: [id], onDelete: Cascade) }

I don't want the user's settings to be optional - is there a way to automatically create the corresponding rows in the settings table when the user is created?

P粉211600174
P粉211600174

reply all (2)
P粉916760429

I'm doing something very similar in my code:

const publication = await prisma.publication.create({ data: { title: e.title, type: e.type, content: e.content, user: { connect: { id: user.id } }, publicationStatus: { create: { status: 'DRAFT' } } } });

All of ourpublicationshave a correspondingpublicationStatus, similar to the question you listed, maybe you can do this:

await prisma.user.create({ data: { settings: { create: { settingOne: true } } } })

or similar operation?

    P粉710454910

    This is impossible, because if both sides of the relationship are required, how can you create either one? So relational aspects without relational scalars (fields that represent foreign keys in the database) must be optional. You can decide which one yourself.

    For example, you want to createUser, butSettingsis required, so you need to createSettingsfirst. But to createSettingsyou also needUserbecause it is required in theSettingsmodel.

    For more information please refer to the documentation

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!