diff --git a/src/Relationships/ManyHasMany.php b/src/Relationships/ManyHasMany.php index c35eeecb..d775f5d4 100644 --- a/src/Relationships/ManyHasMany.php +++ b/src/Relationships/ManyHasMany.php @@ -11,6 +11,8 @@ use Nextras\Orm\Collection\ICollection; use Nextras\Orm\Entity\IEntity; use Traversable; +use function assert; +use function spl_object_hash; class ManyHasMany extends HasMany @@ -43,12 +45,13 @@ public function doPersist() $this->toRemove = []; $this->isModified = false; $this->collection = null; - if ($this->metadataRelationship->isMain) { - $this->getRelationshipMapper()->clearCache(); $this->getRelationshipMapper()->remove($this->parent, $toRemove); $this->getRelationshipMapper()->add($this->parent, $toAdd); } + + $this->getRelationshipMapper()->clearCache(); + $this->relationshipMapper = null; } @@ -106,7 +109,9 @@ protected function updateRelationshipRemove(IEntity $entity): void $otherSide = $entity->getProperty($this->metadataRelationship->property); assert($otherSide instanceof ManyHasMany); $otherSide->collection = null; - $otherSide->toRemove[spl_object_hash($this->parent)] = $this->parent; + $entityHash = spl_object_hash($this->parent); + $otherSide->toRemove[$entityHash] = $this->parent; + unset($otherSide->tracked[$entityHash]); $otherSide->modify(); } } diff --git a/tests/cases/integration/Relationships/relationships.manyHasMany.phpt b/tests/cases/integration/Relationships/relationships.manyHasMany.phpt index fde04a23..a93a179e 100644 --- a/tests/cases/integration/Relationships/relationships.manyHasMany.phpt +++ b/tests/cases/integration/Relationships/relationships.manyHasMany.phpt @@ -238,6 +238,45 @@ class RelationshipManyHasManyTest extends DataTestCase )->orderBy('id'); Assert::same([1, 4], $books->fetchPairs(null, 'id')); } + + + public function testCountAfterRemoveAndFlushAndCount() + { + $book = new Book(); + $book->author = $this->orm->authors->getById(1); + $book->title = 'The Wall'; + $book->publisher = 1; + $book->translator = 1; + + $tag = new Tag('Testing Tag'); + $tag->books->add($book); + + $this->orm->tags->persistAndFlush($tag); + + Assert::same(1, \count($tag->books)); + + foreach ($tag->books as $book) { + $this->orm->books->remove($book); + } + + Assert::same(0, \count($tag->books)); + + $this->orm->books->flush(); + + Assert::same(0, \count($tag->books)); + + $book3 = new Book(); + $book3->author = $this->orm->authors->getById(1); + $book3->title = 'The Wall III'; + $book3->publisher = 1; + $book3->tags->add($tag); + + Assert::same(1, \count($tag->books)); + + $this->orm->books->persist($book3); + + Assert::same(1, \count($tag->books)); + } }