0
votes

I have a relational DB (MySQL) at the backend and cool BackboneJS at the frontend. I have several tables (models in BackboneJS jargon) that are interconnected through foreign keys.

PROBLEM

How do I destroy a specific model, such that destruction cascades to all child models?

EXAMPLE

Consider this quick schema:

PERSON
id
name

PHONE_NUMBER
id
person_id
number

EMAIL_ADDRESS
id
person_id
email

Consider that we have a person "Jack" stored in DB with some phone numbers and email addresses. Also, we have BackboneJS models/collections defined for all of the 3 tables and data is loaded into them. A user on the frontend decides to delete records of Jack with a click.

Now here are a few approaches to delete all records of Jack:

APPROACH#1

Call "destroy" on all models of PhoneNumbers and EmailAddresses related to Jack, then call "destroy" on Jack itself.

Problem(s)

  • Too many AJAX calls for one action.
  • User will have to wait for a lot of time. (More dependants, more time)
  • Deletion will be non-transactional. If user closes the browser during, data will be corrupted.

APPROACH#2

Define foreign key relationships at database level, that ensure cascade deletion of PHONE_NUMBERs and EMAIL_ADDRESSes when a PERSON row is deleted. Then "destroy" BackboneJS model for Jack at frontend.

  • BackboneJS Models for dependants will never know what happened to their corresponding records in the backend. So they'll remain intact.

APPROACH#3

Create a URL on server side application "/thoroughly-delete-person" (which makes sure to delete a person with all of its dependants) and invoke it from the frontend instead of calling BackboneJS's Model#destroy on Jack.

  • Same problem as in Approach#2

So seems like there is no perfect solution for this simple problem. Did you face it too? What approach did you take and why was it better?

1

1 Answers

2
votes

I had a similar problem, and I went with approach #2, except with one difference.

If you can, represent Jack as a single Backbone Model that contains phone_number and email_address. You can pass the Jack model to other Backbone Views to share Jack's model data. You can then call destroy on the Jack model.

On the backend I used an on delete cascade, so I could just make a query:

delete from PERSON where id = JACK_ID;

I don't know the syntax for mysql but something like:

 PERSON
  id
  name

 PHONE_NUMBER
  id  references PERSON (id) on delete cascade
  person_id
  number

 EMAIL_ADDRESS
  id  references PERSON (id) on delete cascade
  person_id
  email

I'm not sure how well this will fit with your current problem context, but this is similar to what I did, and it works for me.