GrumpyHat
GrumpyHat

Reputation: 311

Laravel polymorphic relations / model observers and database integrity

What is the best practice to keep database integrity while using laravel's polymorphic relations?

I'm using Model Observers to update/delete related models. So for example I delete related Documents on "deleted" event while deleting a Customer. That means if an error occurs while deleting first document the rest will stay in the database... Or if I wrap documents deleting in a transaction all of them will stay in the database while parent object is deleted...

Upvotes: 2

Views: 923

Answers (1)

Blackus
Blackus

Reputation: 7203

Unfortunately, there is no good answer for that problem. You can not keep your database integrity with foreign keys because of the polymorphic relation.

One way to try is to use database triggers. As Laravel polymorphic system keep a "type" column on the table that references the related model, you could put a "before delete" trigger on tables that can be morphed to delete all occurences that references the raw you want to delete.

For example, with the structure used in Laravel documentation :

staff
    id - integer
    name - string

orders
    id - integer
    price - integer

photos
    id - integer
    path - string
    imageable_id - integer
    imageable_type - string

You can put an "before delete" trigger on staff table that executes a query (PostgreSQL syntax here) like that :

DELETE FROM photos WHERE imageable_id = OLD.id AND imageable_type = 'staff'

That way, each time you delete a staff raw, all referenced photos will be deleted in the same transaction.

I really don't know if it's the best way to keep integrity with this kind of relation, but it seems to be an efficient one.

Upvotes: 1

Related Questions