我有 UserEntity
和 AddressEntity
,它们的关系为 OneToOne
,也就是说一个用户可能只有一个地址。 UserEntity
有字段 firstName
, secondName
, address
. AddressEntity
有字段 country
和 city
.
如果我想更新 UserEntity
如果不对它的关系做这件事,我会这样做:
await entityManager.getRepository(UserEntity)
.createQueryBuilder('users')
.update(UserEntity)
.set(updateUserObject)
.where('users.id = :userId', { userId })
.execute();
哪里updateUserObject
由请求体构成。也就是说,如果我需要更新firstName
,对象将如下所示:{ firstName: 'Joe' }
.现在不清楚的是如果我有以下 updateUserObject
如何使用该构建器:{
firstName: "Bob",
address: {
"city": "Ottawa"
}
}
官方文档没有解决这种情况。
最佳答案
您可以使用 preload 实现此目的和 save方法。
更新您的 UserEntity
类似于下面:
@Entity('user')
export class UserEntity {
...
@OneToOne(
() => AddressEntity,
{
// Make sure that when you delete or update a user, it will affect the
// corresponding `AddressEntity`
cascade: true,
// Make sure when you use `preload`, `AddressEntity` of the user will also
// return (This means whenever you use any kind of `find` operations on
// `UserEntity`, it would load this entity as well)
eager: true
}
)
@JoinColumn()
address: AddressEntity;
}
正在使用 entityManager
,您可以使用以下方式更新您想要的所有字段:const partialUserEntity = {
id: userId,
firstName: "Bob",
address: {
"city": "Ottawa"
}
};
const userRepository = await entityManager.getRepository(UserEntity);
// Here we load the current user entity value from the database and replace
// all the related values from `partialUserEntity`
const updatedUserEntity = userRepository.preload(partialUserEntity);
// Here we update (create if not exists) `updatedUserEntity` to the database
await userRepository.save(updatedUserEntity);
但是,您需要确保您的 UserEntity
有一个 AddressEntity
始终关联。否则,您将不得不生成 id
为 AddressEntity
执行前如下所示 save
方法。/*
* If `updatedUserEntity.address.id` is `undefined`
*/
// `generateIDForAddress` is a function which would return an `id`
const generatedIDForAddress = generateIDForAddress();
const partialUserEntity = {
id: userId,
firstName: "Bob",
address: {
"id": generatedIDForAddress,
"city": "Ottawa"
}
};
请注意,在底层,typeorm 将运行 UPDATE
UserEntity
的单独声明和 AddressEntity
.这只是对多个join语句(执行preload
方法时)和update语句(执行save
方法时)的封装,这样开发者就可以轻松实现这个场景。希望这对你有帮助。干杯🍻!
关于node.js - 如何在 TypeORM 中使用 QueryBuilder 更新具有关系的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66794387/