如何在TypeORM和Nest.js中删除嵌套实体

时间:2019-08-20 09:42:51

标签: nestjs typeorm

我有一对多的关系:

class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany(() => Phone, phone => phone.user, {cascade: true})
    phones?: Phone[];
}

假设数据库中的当前数据如下:用户有两个电话号码:

{
  "id": 1,
  "name": "Jhon",
  "phones": [
    {"id": 1, "phone":  "123456"},
    {"id": 2, "phone":  "567809"}
  ]
}

我构建了UI(Web界面),并希望从Web界面中删除用户个人资料中的电话号码。因此,我这样做了,以下POST请求来自UI:第二个电话号码已删除

{
  "id": 1,
  "name": "Jhon",
  "phones": [
    {"id": 1, "phone":  "123456"}
  ]
}

如何从数据库中删除电话号码id = 2? 我使用Nest CRUD模块,据我从源代码中了解到,它只是将请求中的新数据与数据库中的当前数据合并,因此将数据库中的两个电话号码与请求中的唯一电话号码合并,可以再次获得一系列电话号码删除:皱眉: 我尝试手动进行操作,并且有很多代码!

  @Override()
  async updateOne(
    @ParsedRequest() req: CrudRequest,
    @ParsedBody() dto: UpdateUserDto,
    @Param('id') id: number,
  ): Promise<Shipment> {

    // use standart Nest.js way to save new user data into database
    await this.service.updateOne(req, dto);

    // load fresh user data from database
    const user = await this.service.findOne(id);

    const phonesFromUi = dto.phones;
    const phonesToBeDeleted = [];
    // loop phone numbers from database - detect which to be deleted
    user.phones.forEach((phoneFromDb) => {
      const hasThisPhoneOnUi = phonesFromUi.find((phoneFromUi) => phoneFromUi.id === phoneFromDb.id);
      if (!hasThisPhoneOnUi) {
        // looks like this phone number was deleted on ui, so delete it from database too
        phonesToBeDeleted.push(phoneFromDb);
      }
    });
    // actually delete phone numbers from database
    await this.connection.getRepositoryFor(Phone).remove(phonesToBeDeleted);

    // reload fresh user data from database to get fresh list of phone numbers after delition some of them
    const user = await this.service.findOne(id);

    return user;
  }

是否可以通过TypeORM内置函数或方法来实现?如何从嵌套数组中删除某些元素?

1 个答案:

答案 0 :(得分:1)

typeorm中没有很好的支持进行联接更新,我建议您做的是接收phones参数并选择与UserId相关的电话,然后删除不在其中的id。新数组:

const phones = await this.phoneRepository.find({userId:1});
const toDeletePhones = phones.filter((element)) => {
  return updatePhones.indexOf(element) === -1;
}
this.phoneRepository.remove(toDeletePhones);

然后继续更新用户,否则您甚至可以在此之前完成