You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建Transaction时出现400错误‘user should not be empty’怎么解决?

创建Transaction时触发400错误:"user should not be empty" 排查与修复

核心问题分析

  • User实体关联字段类型错误
    User类中transactions字段被定义为单个Transaction类型,但@OneToMany关联对应"一对多"关系,正确类型应为Transaction[]。这个错误会导致TypeORM的关联映射逻辑异常,进而影响Transaction与User的关联校验。
  • 关联实体构造方式不正确
    手动构造{user: {id}}这类普通对象,TypeORM可能无法将其识别为有效的User关联实体,导致保存时触发user非空校验失败。
  • 其他潜在问题
    • Category实体主键列名拼写错误:categoty_id应为category_id,会导致数据库列名不匹配;
    • Transaction实体的id使用@PrimaryColumn未设置自增,创建时若未手动赋值会引发主键为空错误。

修复步骤

1. 修正User实体的transactions字段类型

@Entity()
export class User {
  // ... 其他字段
  @OneToMany(() => Transaction, (transaction) => transaction.user, {
    onDelete: 'CASCADE',
  })
  transactions: Transaction[] // 改为数组类型
  // ... 其他字段
}

2. 使用TypeORM的Repository方法创建关联实体

避免手动构造关联对象,改用getReferenceById获取实体引用,确保ORM能正确识别关联:

async create(createTransactionDto: CreateTransactionDto, userId: number) {
  // 获取User和Category的实体引用
  const user = await this.userRepository.getReferenceById(userId);
  const category = await this.categoryRepository.getReferenceById(+createTransactionDto.category);

  // 使用repository.create方法构造Transaction实体
  const newTransaction = this.transactionRepository.create({
    title: createTransactionDto.title,
    amount: createTransactionDto.amount,
    type: createTransactionDto.type,
    category,
    user
  });

  return await this.transactionRepository.save(newTransaction);
}

3. 修正Category实体的主键列名拼写

@Entity()
export class Category {
  @PrimaryGeneratedColumn({ name: 'category_id' }) // 修正拼写为category_id
  id: number
  // ... 其他字段
}

4. 优化Transaction实体的主键配置(可选)

如果希望Transaction的id自动生成,将@PrimaryColumn改为@PrimaryGeneratedColumn:

@Entity()
export class Transaction {
  @PrimaryGeneratedColumn({ name: 'transaction_id' }) // 改为自增主键
  id: number
  // ... 其他字段
}

内容的提问来源于stack exchange,提问作者Goering Novorozzov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 17:17:32