首页 > 解决方案 > TypeORM:通过 Repository 使用关系 (@joinColumn) 更新实体列

问题描述

我有以下实体:

@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   

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

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

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

标签: node.jstypescriptpostgresqlnestjstypeorm

解决方案


我找到了答案,不是在 TypeORM 文档中,而是在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 搜索一个值,你可以通过userIDEntity 的属性来完成。但是,当您join参与其中时,您可以按字段relations[]访问您的对象。user


推荐阅读