Typeorm: Delete Referenced Record instead of setting fk reference to null on OneToMany save

Created on 1 Dec 2017  路  3Comments  路  Source: typeorm/typeorm

Setup:

@Entity()
export Class EntityA extends BaseEntity {
  @PrimaryGeneratedColumn()
  EntityAId: number;

  @Column()
  SomeCol: string;

  @OneToMany(type => EntityB, entity => entity.EntityA, {
    cascadeInsert: true
  })
  EntityBs: EntityB[];
}

@Entity()
export Class EntityB extends BaseEntity {
  @PrimaryGeneratedColumn()
  EntityAId: number;

  @ManyToOne(type => EntityA, (entity: EntityA) => entity.EntityBs)
  @JoinColumn({ name: 'fkEntityA' })
  EntityA: EntityA;
}

...
let entity = await EntityA.findOne({
  SomeCol: 'SomeVal'
});

entity.EntityBs = [
  EntityB.create()
];

entity.save();

Say I already have an EntityA in the database with some EntityBs that reference it.

If I query entityA and then change entity.EntityBs to some new array of EntityBs (and maybe update some existing), the ones that are no longer in the array I want to DELETE from the database.

Right now they only get their fkEntityA reference set to NULL. Is this a feature I can set?

Thanks

(I have tried the cascaseremove on onDelete CASCADE option but the reference record was still just having the value set to NULL)

Most helpful comment

@AlexMesser How to delete related records instead detaching. Because some cases I just update parent entity without deleting.

All 3 comments

If you set onDelete="CASCADE", the related entity is removed only when the owning entity is. Supplying the new array of EntityBs without records that you want to delete causes _detach_, not _delete_ of related records. It means that this records now do not belong to EntityA.

If you want to delete related records, you must manually call entityMenager.remove() on these records.

Looks like question is answered.

@AlexMesser How to delete related records instead detaching. Because some cases I just update parent entity without deleting.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cameronpickham picture cameronpickham  路  3Comments

CocaColaBear picture CocaColaBear  路  3Comments

leixu2txtek picture leixu2txtek  路  3Comments

shotor picture shotor  路  3Comments

Diluka picture Diluka  路  3Comments