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

Alb*_*ert 6 node.js typeorm nestjs

我有UserEntityAddressEntity,它们是相关的OneToOne,即一个用户可能只有一个地址。UserEntity有字段firstName, secondName, addressAddressEntity有字段countrycity.

如果我想更新UserEntity而不对其关系进行更新,我会这样做:

      await entityManager.getRepository(UserEntity)
                         .createQueryBuilder('users')
                         .update(UserEntity)
                         .set(updateUserObject)
                         .where('users.id = :userId', { userId })
                         .execute();
Run Code Online (Sandbox Code Playgroud)

其中updateUserObject由请求正文组成。也就是说,如果我需要更新firstName,该对象将如下所示:{ firstName: 'Joe' }。现在不清楚的是,如果我有以下内容,如何使用该构建器updateUserObject

{
    firstName: "Bob",
    address: {
        "city": "Ottawa"
    }
}
Run Code Online (Sandbox Code Playgroud)

官方文档没有解决此类情况。

Era*_*han 10

您可以使用预加载保存方法来实现此目的。

更新您的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;
}
Run Code Online (Sandbox Code Playgroud)

现在使用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 = await userRepository.preload(partialUserEntity);

// Here we update (create if not exists) `updatedUserEntity` to the database
await userRepository.save(updatedUserEntity);
Run Code Online (Sandbox Code Playgroud)

但是,您需要确保您始终UserEntityAddressEntity关联。否则,在执行方法之前,您必须生成如下所示的idfor 。AddressEntitysave

/* 
 * 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"
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,在底层,typeorm 将分别为和运行UPDATE语句。这只是对多个join语句(执行方法时)和update语句(执行方法时)的封装,以便开发者可以轻松实现该场景。UserEntityAddressEntitypreloadsave

希望这对您有帮助。干杯!