Prisma 在创建父项时自动创建相关行

Prisma automatically create related row when parent is created

我有一个看起来像这样的架构

model User {
  id       Int      @default(autoincrement())
  settings Settings
}

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

我不希望用户中的设置是可选的 - 有没有一种方法可以在创建用户时自动在设置 table 中创建相应的行?

这是不可能的,因为如果关系的两边都需要那么你将如何创建它们?因此,没有关系标量的关系的一侧(表示数据库中外键的字段)必须是可选的。不过你可以自己决定选择哪一个。

比如你想创建User,但是需要Settings,所以你需要先创建Settings。但是要创建 Settings,您还需要 User,因为 Settings 模型需要它。

More info in the docs

我正在做一些与我非常相似的事情:

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

或类似的东西?