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

标签 node.js nestjs typeorm

我有 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/

相关文章:

javascript - 如何使用 Jest 对 typeorm getRepository 进行单元测试?

node.js - Sequelize 关联

javascript - 根据参数注入(inject)正确的服务

javascript - 发送多部分发布请求时出现问题

angular - 使用 Nestjs/Angular 初始化 MongoDB 时出错

typescript - nestjs 如何工作并使用参数运行构造函数

nestjs - 如何让 Inner Join 在 TypeORM 上工作?

express - 使用 type-graphql typeorm 和 dataloader 处理一对多的最佳方法

android - 使用 Nodejs + SocketIO 时丢弃传输错误

node.js - MongoDB 的随机 CursorNotFound 错误