doctrine / orm

Doctrine Object Relational Mapper (ORM)
https://www.doctrine-project.org/projects/orm.html
MIT License
9.94k stars 2.52k forks source link

Cascade detach should detach lazy collections too #11717

Open goetas opened 6 days ago

goetas commented 6 days ago

This is a follow up of https://github.com/doctrine/orm/pull/10065

When a collection is "LAZY", it is not being detached when detach is called.

In order to detach all the entities, the collection needs to be initialized (similarly to what is done for remove()).

To give a more real example:

Given this class:

class User
{
    /**
     * @ORM\OneToMany(targetEntity="Address", cascade={"detach"}, fetch="LAZY")
     */
    public $addresses;
}

before my change

$user = $em->find(User::class, $user->id);
$em->detach($user);

$adr1 = $user->addresses[0]; 
// this will trigger an SQL query to fin the address 
// but it should not happen because the user is detached, addresses should be detached as well

$m->contains($adr1); // is managed ... but it should have been detached

after my change

$user = $em->find(User::class, $user->id);
$em->detach($user);

$adr1 = $user->addresses[0];  // no SQL triggered at this point

$m->contains($adr1); // not managed