Heim  >  Fragen und Antworten  >  Hauptteil

Prisma erstellt automatisch verwandte Zeilen, wenn das übergeordnete Element erstellt wird

<p>Ich habe ein ähnliches Muster</p> <pre class="brush:php;toolbar:false;">model Benutzer { id Int @default(autoincrement()) EinstellungenEinstellungen } Modelleinstellungen { Benutzer-ID Int SettingOne Boolean @default(false) user User @relation(fields: [userId], references: [id], onDelete: Cascade) }</pre> <p>Ich möchte nicht, dass die Einstellungen des Benutzers optional sind. Gibt es eine Möglichkeit, die entsprechenden Zeilen in der Einstellungstabelle automatisch zu erstellen, wenn der Benutzer erstellt wird? </p>
P粉211600174P粉211600174420 Tage vor386

Antworte allen(2)Ich werde antworten

  • P粉916760429

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

    我在我的代码中正在做非常类似的事情:

    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'
                }
            }
        }
    });
    

    我们所有的publications都有一个对应的publicationStatus,类似于你列出的问题,也许你可以这样做:

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

    或者类似的操作?

    Antwort
    0
  • P粉710454910

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

    这是不可能的,因为如果关系的两个方面都是必需的,那么你如何创建其中任何一个呢?所以没有关系标量(表示数据库中外键的字段)的关系方面必须是可选的。你可以自己决定哪一个。

    例如,你想创建User,但Settings是必需的,所以你需要先创建Settings。但是要创建Settings,你也需要User,因为它在Settings模型中是必需的。

    更多信息请参阅文档

    Antwort
    0
  • StornierenAntwort