创建记录时出现未知参数错误

Unknown argument error when creating record

我在使用 Prisma ORM 时遇到了一些有趣的行为。它与 Prisma 的生成类型有关,我一直在浏览文档试图找到更多信息,但那里似乎没有太多关于生成类型的信息(如果我弄错了请纠正我)。这是行为:

假设我有一个具有两个 1-1 关系的模型(下例中的Profile):

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id      Int      @id @default(autoincrement())
  name    String
  profile Profile?
}

model Profile {
  id      Int    @id @default(autoincrement())
  name    String
  userId  Int?
  user    User?  @relation(fields: [userId], references: [id])
  photoId Int?
  photo   Photo? @relation(fields: [photoId], references: [id])
}

model Photo {
  id      Int      @id @default(autoincrement())
  url     String
  profile Profile?
}

以下代码在创建新配置文件时有效:

const user = await prisma.user.create({ data: { name: "TestUser" } });    
const profile = await prisma.profile.create({
  data: {
    name: "TestProfile",
    user: { connect: { id: user.id } },
    photo: { create: { url: "http://example.com/img" } },
  },
});

...但这失败并出现错误:

const user = await prisma.user.create({ data: { name: "TestUser" } });
const profile = await prisma.profile.create({
  data: {
    name: "TestProfile",
    userId: user.id,
    photo: { create: { url: "http://example.com/img" } },
  },
});

错误是:

Unknown arg userId in data.userId for type ProfileCreateInput. Did you mean user? Available args:
type ProfileCreateInput {
  name: String
  user?: UserCreateNestedOneWithoutProfileInput
  photo?: PhotoCreateNestedOneWithoutProfileInput
}

为什么第二个create-profile代码无效?

Prisma 本质上为 create 查询生成两个类型定义。这是用 XOR 类型实现的,它确保两个定义中只有一个定义被完全指定并传递给查询:

export type ProfileCreateArgs = {
  ...
  data: XOR<ProfileCreateInput, ProfileUncheckedCreateInput>;
}

定义被称为选中和未选中,前者使用嵌套字段,后者使用原始 ID:

export type ProfileCreateInput = {
  id?: number;
  ...
  user?: UserCreateNestedOneWithoutProfileInput;
  photo?: PhotoCreateNestedOneWithoutProfileInput;
}

export type ProfileUncheckedCreateInput = {
  id?: number;
  ...
  userId?: number;
  photoId?: number;
}

这基本上意味着您要么将所有引用提供为 connectcreate 等关系(选中)或原始 ID(未选中)。不能混合样式,不支持。