使用Prisma.create创建Computer记录时关联Employee出现参数不合法错误的求助
解决Prisma创建关联数据时的字段错误问题
我来帮你搞定这个问题!你遇到的错误核心是Prisma对于关联字段的操作有严格的语法要求——不能直接传递实体的字段值,必须用它规定的关键字来明确是连接已有记录还是创建新记录。
错误原因分析
从报错信息能看出来,EmployeeCreateNestedOneWithoutComputerInput这个类型只接受create、connectOrCreate、connect这几个参数,而你直接传入了id、name这些Employee的字段,完全不符合Prisma的关联语法规则。
解决方案
你的需求应该是把新创建的Computer关联到已存在的Employee,所以需要用connect关键字来指定要关联的Employee的唯一标识(这里是id)。
1. 修改前端关联字段的写法
把你Angular代码里createComputer方法中data对象里的关联字段(包括employee和其他如office_key、processor等)都改成connect格式:
原来的错误写法:
employee: { id: this.employee.value.id, }, office_key: { id: this.office_key.value.id, },
修正后的写法:
employee: { connect: { id: this.employee.value.id } }, office_key: { connect: { id: this.office_key.value.id } },
2. 完整修正后的前端data代码
createComputer(): void { let data: any = { description: this.description.value, erp: false, office_key: { connect: { id: this.office_key.value.id } }, office_version: { connect: { id: this.office_version.value.id } }, processor: { connect: { id: this.processor.value.id } }, memory: { connect: { id: this.memory.value.id } }, disk: { connect: { id: this.disk.value.id } }, license: { connect: { id: this.license.value.id } }, brand: { connect: { id: this.brand.value.id } }, manufacturer: { connect: { id: this.manufacturer.value.id } }, employee: { connect: { id: this.employee.value.id } }, os: { connect: { id: this.os.value.id } }, sector_id: 1, type: { connect: { id: this.type.value.id } }, }; try { this.computerService.create(data).subscribe(() => { console.log("Registro criado"); this.dialogRef.close({ created: "ok" }); }); } catch (e) { console.log(`Erro: ${e}`); } }
补充说明
Prisma的嵌套关联操作有三种常用模式,你可以根据场景选择:
connect: 关联已存在的记录,必须传入该记录的唯一标识(比如id)create: 创建新的关联记录并绑定到当前实体connectOrCreate: 如果目标记录存在则关联,不存在则创建后再关联
你的场景显然是关联已有员工,所以connect是最适合的选择。
内容的提问来源于stack exchange,提问作者Ari
相关产品推荐
相关产品推荐

