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
我喜欢wallet
通过 Repository api 更新实体。但问题是,我不能只是:
WalletRepository.save({ address: '0x12', userId: 2 })
因为 Typescript 给我一个错误,那userId
应该是userEntity
,但不是数字。但我想更新一个关系列。那么有没有办法更新呢?
解决方案
我找到了答案,不是在 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 搜索一个值,你可以通过userID
Entity 的属性来完成。但是,当您join
参与其中时,您可以按字段relations[]
访问您的对象。user
推荐阅读
- linux - linux查找文件绝对路径问题
- google-cloud-platform - GCP 问题 GKE HPA 无法读取指标值
- symfony - 如何在任何类中注入 EntityManagerInterface(特别是命令助手)
- python - 从列表理解中的列表中仅删除一次
- javascript - Javascript;删除 HTML 中没有对应的特定图像
- python-3.x - 如何在 Bokeh 1.1.0 的次要代码中显示值
- python - Python:如何根据同一实例的另一个属性的布尔值自动更改实例的属性?
- reactjs - React:如何正确更新状态数组?setState(state.concat(array)) 不工作
- php - jquery 选择器停止工作问题因为 #&ui-state=dialog data-history="false" 没有工作
- javascript - 如何使用 OR (||) 逻辑运算符验证用户输入 ID 是石头、纸还是剪刀?