NestJS+TypeORM配置OneToMany关系插入数据外键userId为NULL如何解决
解决方案
- 首先检查传入的
user参数是否为已持久化的实体实例,确保user.id存在且有有效值。如果user是未保存到数据库的临时对象,外键无法正常生成。 - 移除Account实体中
@CreateDateColumn、@UpdateDateColumn上多余的@Column装饰器,这两个装饰器本身已包含列定义逻辑,重复声明会导致字段映射异常。 - 在Account实体中显式声明外键列,避免TypeORM隐式生成的列无法正常映射:
@Entity() export class Account extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column({ unique: true }) apikey: string; @Column({ unique: true }) apikeysecret: string; // 移除多余的@Column @CreateDateColumn() createdAt: Date; // 移除多余的@Column @UpdateDateColumn() updatedAt: Date; @Column() exchange: string; // 新增显式外键列声明 @Column() userid: number; @ManyToOne(() => User, (user: User) => user.accountsaccounts, { onUpdate: 'CASCADE', onDelete: 'CASCADE', }) @JoinColumn({ name: 'userid', referencedColumnName: 'id' }) public useruser: User; } - 修改新增逻辑,直接给显式声明的外键列赋值,比赋值关联实体更稳定,避免TypeORM对plain对象识别异常的问题:
async create(createAccountDto: CreateAccountDto, user: User) { const { apikey, apikeysecret, exchange } = createAccountDto; if (await this.findByApikeyAndSecret(apikey, apikeysecret)) { throw new HttpException( 'Account with these api key and api key secret already exists', HttpStatus.UNPROCESSABLE_ENTITY, ); } const account = new Account(); account.apikey = apikey; account.apikeysecret = apikeysecret; account.exchange = exchange; // 直接赋值外键ID,无需依赖关联实体映射 account.userid = user.id; return await this.accountRepository.save(account); } - 你注释掉的save写法错误是因为关联属性名不匹配,实体中关联属性名为
useruser,你传入的字段为user,如果要使用该写法需修改为:return await this.accountRepository.save({ ...createAccountDto, useruser: user, });
内容的提问来源于stack exchange,提问作者Luca Valsecchi
相关产品推荐
相关产品推荐

