使用TypeORM和MySQL为可选参数设置null的问题求助
解决思路与方案
问题根源
你遇到的是TypeGraphQL类型推断和TypeORM类型兼容的双重问题:
- ObjectType中添加
| null后,TypeGraphQL无法自动推断GraphQL类型,必须显式声明 - InputType的
string | null | undefined类型与TypeORM更新时的QueryDeepPartialEntity类型不兼容
步骤1:修正ObjectType的类型定义
给gender和birthday字段显式指定GraphQL类型,并同步TypeScript类型为string | null(与数据库字段的default: null对齐):
@ObjectType() export class User { // 其他字段... @Field(() => String, { nullable: true }) @Column({ default: null }) gender?: string | null; @Field(() => String, { nullable: true }) @Column({ default: null, type: 'date' }) birthday?: string | null; }
注意:必须在
@Field中传入() => String显式声明类型,仅设置nullable: true不足以让TypeGraphQL识别string | null的联合类型。
步骤2:保持InputType的兼容性
你的InputType定义是合理的,?允许字段未传入(undefined),| null允许传入明确的null值,配合@Field({ nullable: true })完全符合GraphQL的nullable规则:
@InputType() export class UserEditAccountDetailsInput { @Field() email: string; @Field(() => String, { nullable: true }) birthday?: string | null; @Field(() => String, { nullable: true }) gender?: string | null; }
步骤3:解决TypeORM更新的类型冲突
TypeORM的update方法对undefined字段的处理存在类型限制,你需要在Resolver中过滤掉undefined的字段,只保留需要更新的有效值(包括null):
@Mutation(() => User) async editUserAccount( @Args('input') input: UserEditAccountDetailsInput, @Ctx() ctx: Context, // 假设你有上下文获取用户ID ) { // 过滤undefined字段,只保留需要更新的键值对 const updatePayload = Object.fromEntries( Object.entries(input).filter(([_, value]) => value !== undefined) ); // 执行更新 await this.userRepository.update(ctx.userId, updatePayload); // 返回更新后的用户信息 return this.userRepository.findOneBy({ id: ctx.userId }); }
这样处理后,TypeORM接收的updatePayload不会包含undefined字段,完美匹配QueryDeepPartialEntity的类型要求。
内容的提问来源于stack exchange,提问作者Cătălin Avasiloaie
相关产品推荐
相关产品推荐

