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)
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.
Most helpful comment
@AlexMesser How to delete related records instead detaching. Because some cases I just update parent entity without deleting.