【问题标题】:TypeORM: update entity column with relation (@joinColumn) via RepositoryTypeORM:通过 Repository 使用关系 (@joinColumn) 更新实体列
【发布时间】:2021-07-16 14:47:07
【问题描述】:

我有以下实体:

@Entity({ name: 'user' })
export class UserEntity extends BasicEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    nullable: false,
    unique: true,
  })
  login: string;
}
@Entity({ name: 'wallet' })
export class WalletEntity extends BasicEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToOne(() => UserEntity)
  @JoinColumn({ name: 'user_id' })
  user: UserEntity;

  @Column({
    name: 'address',
    type: 'text',
  })
  address: string;
}

所以,钱包表是这样的:

-------------------------
 id | user_id | address
-------------------------
 1  |    1    |   0x12   
-------------------------
 2  |    43    |  0x10   

我喜欢通过 Repository api 更新 wallet 实体。但问题是,我不能只是:

WalletRepository.save({ address: '0x12', userId: 2 })

因为 Typescript 给我一个错误,所以 userId 应该是 userEntity,而不是数字。但我想更新一个关系列。那么有没有办法更新呢?

【问题讨论】:

    标签: node.js typescript postgresql nestjs typeorm


    【解决方案1】:

    我找到了答案,不是在 TypeORM 文档中,而是在 issues Github post

    所以我需要两列:

    @Entity({ name: 'wallet' })
    export class WalletEntity extends BasicEntity {
      @PrimaryGeneratedColumn()
      id: number;
    
      @ManyToOne(() => UserEntity, (entity: UserEntity) => entity.id)
      @JoinColumn({ name: 'user_id' })
      user: UserEntity;
    
      @Column({ name: 'user_id', type: 'int' })
      userId: number;
    
      @Column({
        name: 'address',
        type: 'text',
      })
      address: string;
    }
    

    {name: user_id} 一个用于关系,另一个用于关系更新或查找值。这很不明显。所以如果你想通过这个关系 ID 搜索一个值,你可以通过实体的userID 属性来完成。但是当你在做join 部分时,使用relations[],你可以通过user 字段访问你的对象。

    【讨论】:

    • 感谢您发布您的发现,在这方面可以找到很少的文档
    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2021-06-02
    • 2018-09-10
    • 1970-01-01
    • 2020-01-01
    • 2014-08-17
    相关资源
    最近更新 更多