S
S
Seintero2017-03-29 17:34:23
symfony
Seintero, 2017-03-29 17:34:23

Doctrine OneToMany and ManyToOne, how to write cascading deletion?

I can not achieve in any way that when deleting one entity, the key in the entity associated with it is nullified. for example

/**  
     * @ORM\OneToMany(targetEntity="User", mappedBy="division")
     */
    private $users;

/**
     * @ORM\ManyToOne(targetEntity="Division", inversedBy="users")
     * @ORM\JoinColumn(name="division_id", referencedColumnName="id", onDelete="SET NULL")
     */
    private $division;

Those. I want that when Division is deleted, the user entity is not deleted, but its division_id key is reset to zero. And I can't beat it. If you write cascade={"remove"} from the OneToMany side, then all entities will be deleted, and this is not exactly what interests me. I hope someone will be able to suggest how this is properly organized at the level of doctrine? :(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis, 2017-03-30
@prototype_denis

onDelete and others in JoinColumn - executed on the database side
(Check the database for this value - 99% that the cascade operation for deletion hangs in the database itself)
cascade={...} This is a programmatic implementation of these events (Driven by doctrine)
In your case , even if you remove all the doctrine settings for cascading operations, I'm sure that the associated entity will still be deleted, so the doctrine has nothing to do with it.

I
iddqd3, 2019-04-11
@iddqd3

class User {
     /**  
     * @ORM\OneToMany(targetEntity="Division", mappedBy="division")
     */
    private $users;
}

class Division {
     /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="users")
     * @ORM\JoinColumn(name="division_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $division;
}

When the User is deleted, all Divisions will be deleted, but when one Division is deleted, the $users field will not be NULL because the User table will not even have a division field.
To check for emptiness, you will need to do something like this
$user->getUsers()->isEmpty()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question