Skip to content

Delete entity on OneToMany update #5645

@hpohlmeyer

Description

@hpohlmeyer

Issue type:

[x] question
[ ] bug report
[ ] feature request
[ ] documentation issue

Database system/driver:

[ ] cordova
[ ] mongodb
[ ] mssql
[ ] mysql / mariadb
[ ] oracle
[x] postgres
[ ] cockroachdb
[ ] sqlite
[ ] sqljs
[ ] react-native
[ ] expo

TypeORM version:

[x] latest
[ ] @next
[ ] 0.x.x (or put your version here)


I am looking for a way to delete an entity by updating a OneToMany relation with cascades in typorm. I know, I could do this by diffing the changes and deleting the referenced entity by hand, but since typorm already knows which changes have happened, it would be nice it could also handle this case.

I could not figure out how to do it, or if it is even possible with typeorm right now.

I think the best way to explain my problem is through an example:

Starting point

// Booker Entity
{
  @OneToMany(
        (type) => Attendee,
        (attendee) => attendee.booker,
        {
            nullable: true,
            cascade: ["insert", "update", "remove"],
        },
    )
    attendees?: Array<Attendee>;
}
// Attendee Entity
{
  @ManyToOne(
      (type) => Booker,
      (booker) => booker.attendees,
  )
  booker!: Booker;
}

Booker table

id firstname lastname
1 Jane Doe

Attendee table

id firstname lastname bookerId
2 June Doe 1
3 Joe Doe 1

My steps

const booker = bookerRepository.create({
  id: 1,
  firstname: "Jane",
  lastname: "Doe",
  attendees: [{
    id: 3,
    firstname: "Joe",
    lastname: "Doe"
  }]
});

bookerRepository.save(booker);

Current outcome

  1. save realizes which entity is missing
  2. TypeORM tries to set the the bookerId of the removed row (id 2) to null`
  3. Error because of a foreign key violation

Expected outcome

  1. save realizes which entity is missing
  2. TypeORM deletes the row which has been removed from the payload (id 2)

The final state should look like this:

Booker table

id firstname lastname
1 Jane Doe

Attendee table

id firstname lastname bookerId
3 Joe Doe 1

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions