Home  >  Q&A  >  body text

Prisma automatically creates related rows when the parent is created

<p>I have a pattern similar to this</p> <pre class="brush:php;toolbar:false;">model User { id Int @default(autoincrement()) settingsSettings } model Settings { userId Int settingOne Boolean @default(false) user User @relation(fields: [userId], references: [id], onDelete: Cascade) }</pre> <p>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>
P粉211600174P粉211600174420 days ago390

reply all(2)I'll reply

  • P粉916760429

    P粉9167604292023-08-27 15:43:23

    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 our publications have a corresponding publicationStatus, similar to the question you listed, maybe you can do this:

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

    or similar operation?

    reply
    0
  • P粉710454910

    P粉7104549102023-08-27 12:46:38

    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 create User, but Settings is required, so you need to create Settings first. But to create Settings you also need User because it is required in the Settings model.

    For more information please refer to the documentation

    reply
    0
  • Cancelreply