Prisma automatically creates related rows when the parent is created
P粉211600174
P粉211600174 2023-08-26 19:19:48
0
2
407
<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粉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 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?

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 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

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!