Skip to content

Commit

Permalink
cascade detach should detach lazy collections too
Browse files Browse the repository at this point in the history
  • Loading branch information
goetas committed Nov 15, 2024
1 parent 486e406 commit 75fa53c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 7 deletions.
6 changes: 1 addition & 5 deletions src/UnitOfWork.php
Original file line number Diff line number Diff line change
Expand Up @@ -2548,11 +2548,7 @@ static function ($assoc) {
$relatedEntities = $class->reflFields[$assoc['fieldName']]->getValue($entity);

switch (true) {
case $relatedEntities instanceof PersistentCollection:
// Unwrap so that foreach() does not initialize
$relatedEntities = $relatedEntities->unwrap();
// break; is commented intentionally!

// in order to detach the entities in the collection, initialization is needed (no unwrap)
case $relatedEntities instanceof Collection:
case is_array($relatedEntities):
foreach ($relatedEntities as $relatedEntity) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,36 @@ public function testRefreshRefreshesBothLazyAndEagerCollections(): void
self::assertSame('12345', $ph->data);
self::assertSame('6789', $ad->data);
}

public function testCascadeDetachBothLazyAndEagerCollections(): void
{
$user = new LazyEagerCollectionUser();
$user->data = 'Guilherme';

$ph = new LazyEagerCollectionPhone();
$ph->data = '12345';
$user->addPhone($ph);

$ad = new LazyEagerCollectionAddress();
$ad->data = '6789';
$user->addAddress($ad);

$this->_em->persist($user);
$this->_em->persist($ad);
$this->_em->persist($ph);
$this->_em->flush();
$this->_em->clear();

$user = $this->_em->find(LazyEagerCollectionUser::class, $user->id);
$this->_em->detach($user);

$ph = $user->phones[0];
$ad = $user->addresses[0];

self::assertFalse($this->_em->contains($user));
self::assertFalse($this->_em->contains($ph));
self::assertFalse($this->_em->contains($ad));
}
}

/**
Expand All @@ -78,14 +108,14 @@ class LazyEagerCollectionUser
public $data;

/**
* @ORM\OneToMany(targetEntity="LazyEagerCollectionPhone", cascade={"refresh"}, fetch="EAGER", mappedBy="user")
* @ORM\OneToMany(targetEntity="LazyEagerCollectionPhone", cascade={"refresh", "detach"}, fetch="EAGER", mappedBy="user")
*
* @var LazyEagerCollectionPhone[]
*/
public $phones;

/**
* @ORM\OneToMany(targetEntity="LazyEagerCollectionAddress", cascade={"refresh"}, mappedBy="user")
* @ORM\OneToMany(targetEntity="LazyEagerCollectionAddress", cascade={"refresh", "detach"}, mappedBy="user")
*
* @var LazyEagerCollectionAddress[]
*/
Expand Down

0 comments on commit 75fa53c

Please sign in to comment.