laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Enforcing foreign key constraints in polymorphic relationships, a different take to keep referential integrity at database level #2514

Closed Aridez closed 3 years ago

Aridez commented 3 years ago

Right now polymorphic relationships in Laravel do not have any referential integrity since they are implemented with two fields that may hold arbitrary values, a string pointing to the destination table and an integer with the ID on that table:

Parent_table
    id - PRIMARY
    destinarion_table_name - string
    destination_id - integer
    [...]

Polymorphic_tables
    id - PRIMARY
    [...]

Instead, polymorphic relationships could be implemented as follows:

Parent_table
    id - PRIMARY
    destinarion_table_name - string

Polymorphic_table
    id - PRIMARY
    parent_id - FK (Parent_table)

On the parent table there's the same information needed to find your polymorphic table (its name and its ID), and referential integrity could now be kept on the polymorphic table due to it having a foreign key constraint. This would help with things such as supporting CASCADE deletions on polymorphic relationships, that now rely on observers.