'TypeORM Insert Cascade no effect

I Have a parent entity CostCenter that contains an Array of Coordinators, coordinators: Array<Coordinator> and this attribute has the typeORM annotations as follows

export class CostCenter {
...
@OneToMany(() => Coordinator, (coordinator) => coordinator.costCenter, {
    eager: true,
    cascade: ['insert', 'update'],
  })
  coordinators: Array<Coordinator>;
...
}

And my coordinator is as follows:

export class Coordinator {
...
  @ManyToOne(() => CostCenter, (costCenter) => costCenter.coordinators, {
    cascade: ['insert', 'update'],
  })
  costCenter: CostCenter;
...
}

And I am trying to save a CostCenter that contains the array of coordinators:

async create(createCostCenterDto: CreateCostCenterDto) {
    const costCenter = new CostCenter(
      createCostCenterDto.code,
      createCostCenterDto.description,
      createCostCenterDto.id,
    );

    var coordinators = new Array<Coordinator>();
    await createCostCenterDto.coordinators.forEach((coordinator) => {
      coordinators.push(
        new Coordinator(
          coordinator.name,
          coordinator.email,
          coordinator.password,
          coordinator.id,
          coordinator.telephone,
          coordinator.registration,
          coordinator.course,
          coordinator.graduation,
        ),
      );
      this.coordinatorRepository.save(coordinator);
    });

    costCenter.coordinators = coordinators;
    return this.costCentersRepository.insert(costCenter);
  }

Following the instructions of the typeORM(https://typeorm.io/#/relations/cascades) documentation this code should work, however this code is saving both entities and the coordinator that should contain the foreing key of costCenter does not receive it. I also tried commenting the line: this.coordinatorRepository.save(coordinator); after commenting it, the cascade did not work at all, it saves the costCenter but not the coordinators.

Any help would be much appreciated



Solution 1:[1]

TypeORM makes a distinction between low level methods that implement the main SQL keywords vs more higher level functions which also trigger cascade.

The case being that save unlike insert triggers cascade.

From the docs:

/**
* Inserts a given entity into the database.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient INSERT query.
* Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
*/
insert(entity: QueryDeepPartialEntity | (QueryDeepPartialEntity[])): Promise;

A similar distinction exists between the repository's remove and delete methods.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gvozden Miskovic