Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core data deleting rules

My database has 3 entities: photos, places (where photos are taken) and tags (of photos).

database

Each photo has a relationship to the place in which it has been taken. Each place has a set of photos taken in it.

Each photo has a set of tags, and each tag has a set of photos. This is a many-to-many relationship, because a single photo can have multiple tags, and a tag can be associated with multiple photos.

Now, I can't figure out the right deleting rules for this behaviour:

  • I want to directly delete only photo entities.
  • If the related place has other photos taken in it, it should not be deleted. If the photo was the last photo for that place, it should be deleted.
  • It the related tags appears in other photos, they should not be deleted until there are no other photos associated.
  • In addition, in the tag entity I have an attribute that keep track of the number of photos associated with it (I update this attribute when I add a new photos and also in photo's prepareForDeletion).

Any suggestion?

like image 388
Ciampo Avatar asked Jan 24 '26 12:01

Ciampo


1 Answers

First, the tag should not need a separate attribute to keep track of the number of photos. You can query the relationship for that count.

Second, you would want to set up a -prepareForDeletion in the Photo entity that checks to see if it is the only photo with a reference to the tag and then deletes it if that is true.

Likewise, when you delete the photo, in its -prepareForDeletion you can check to see how many photos are in that place and invoke the same logic.

In the model itself I would then set the delete rule to just be nullify.

like image 121
Marcus S. Zarra Avatar answered Jan 26 '26 02:01

Marcus S. Zarra