I has three entities: User, WeekDay, TimeSection. User has many WeekDay, but every WeekDay related to one User:
@Entity()
export default class User {
...
@OneToMany(() => WeekDay, (weekDay: WeekDay) => weekDay.user, {
cascade: true,
onDelete: "CASCADE",
onUpdate: "CASCADE",
})
shedule: WeekDay[]
...
}
@Entity()
export default class WeekDay {
...
@ManyToOne(() => User, (user: User) => user.shedule, {
onDelete: "CASCADE",
orphanedRowAction: "delete",
})
user: User
...
}
Also, every WeekDay related to one TimeSection, and every TimeSection related to one WeekDay:
@Entity()
export default class WeekDay {
...
@OneToOne(() => TimeSection, (timeSection) => timeSection.week_day, {
cascade: true,
onDelete: "CASCADE",
onUpdate: "CASCADE",
})
@JoinColumn()
time_section: TimeSection
...
}
@Entity()
export default class TimeSection {
...
@OneToOne(() => WeekDay, (weekDay) => weekDay.time_section, {
onDelete: "CASCADE",
})
week_day: WeekDay
...
}
At the moment, I’m only working with the User entity, expecting that all updates to the shedule and time_section inside the shedule will be performed automatically. That’s how I update User entity:
async update(body: UpdateUserDto) {
const user = await this.users.findOne({
where: { id: body.id },
relations: ["shedule", "shedule.time_section"],
})
user.shedule = body.shedule
await this.users.save(user)
return user
}
WeekDay entities are updated correctly – if before the update I had two records in the database linked to a user entity, and then passed an empty shedule array to update this user entity, both records will be deleted as expected. However, the TimeSection entities associated with them are not deleted.
I have tried many combinations of relation properties- eager, cascade, on Delete, onUpdate, none of them worked.