Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable cascade deletion for many-to-many relations?

For a Many-to-Many relations (say Groups and Users) the rows from the joint table are automatically removed as soon as either of the entities is deleted, like the cascade remove attribute was set for the relation. So basically I want to delete it IF ONLY IT IS EMPTY. So the solution must guarantee no relations were dropped (exactly like FK constraint guarantees it).

Is it possible to not do that by default and throw an exception on foreign key constraint violation?

PS: checking before deletion is not a solution since it's a race condition prone.

PPS: mapping definitions are trivial, for the sake of completeness I post them here (even though they don't bring anything useful)

PPPS: onDelete: cascade is not a solution either: it creates the corresponding ON DELETE CASCADE on the database level.

PPPPS: ON DELETE RESTRICT CANNOT BE USED since doctrine will remove all the references from the joint table.

In roles:

manyToMany:
    users:
        targetEntity: UserAccount
        mappedBy: roles

In users:

manyToMany:
    roles:
        targetEntity: Role
        joinTable:
            name: user_role
            joinColumns:
                user_id:
                    referencedColumnName: id
            inverseJoinColumns:
                role_id:
                    referencedColumnName: id
like image 421
zerkms Avatar asked Apr 20 '15 00:04

zerkms


1 Answers

This answer can be considered as a workaround. The many-to-many association can be replaced by one-to-many/many-to-one associations between the 3 participating classes, because Doctrine has no cascade deleting with one-to-many by default.

one-to-many/many-to-one

like image 88
Serge Kvashnin Avatar answered Oct 21 '22 04:10

Serge Kvashnin