node.js - 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
而且我喜歡通過 Repository API 更新 wallet 實體。但問題是,我不能只是這樣:
WalletRepository.save({ address: '0x12', userId: 2 })
因為 Typescript 給我一個錯誤,指出 userId 應該是 userEntity,而不是數字。但我想更新一個關聯欄位。所以有沒有任何選項可以更新它?
答案#1
我找到了一個答案,不是在 TypeORM 文件中,而是在 GitHub 的問題貼文中。
所以我需要兩列:
@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 欄位訪問你的對象。
