Search code examples
node.jstypescriptpostgresqlnestjstypeorm

TypeORM: update entity column with relation (@joinColumn) via Repository


I have the following entities:

@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;
}

So, the wallet table is looks like this:

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

And I like to update the wallet entity via Repository api. But the problem is, that I can't just:

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

Because Typescript give me an error, that userId should be userEntity, but not number. But I want to update a relation column. So is there any option to update it?


Solution

  • I found an answer, not in TypeORM docs, but issues Github post.

    So I need two columns:

    @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;
    }
    

    with {name: user_id} one is for relation, another is for relation update or find value. Which pretty unobvious. So if you want to search for a value by this relation ID, you could do it by the userID property of the Entity. But when you are doing join part, with relations[], you can access your object by user field.