Skip to content

Commit

Permalink
relationship/manyHasMany: fixed tracking & cache invalidation [closes #…
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach committed Apr 10, 2020
1 parent 8f98094 commit 3ff59e1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Relationships/ManyHasMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}


Expand Down Expand Up @@ -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();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
}


Expand Down

0 comments on commit 3ff59e1

Please sign in to comment.