gpt4 book ai didi

node.js - 如何在 TypeORM 中使用 QueryBuilder 更新具有关系的实体

转载 作者:行者123 更新时间:2023-12-04 17:19:55 24 4
gpt4 key购买 nike

我有 UserEntityAddressEntity ,它们的关系为 OneToOne ,也就是说一个用户可能只有一个地址。 UserEntity有字段 firstName , secondName , address . AddressEntity有字段 countrycity .
如果我想更新 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始终关联。否则,您将不得不生成 idAddressEntity执行前如下所示 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com