Skip to content

Commit

Permalink
do not attach removed entities when using them in HasMany::has()
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach committed Jan 4, 2025
1 parent 57f8abe commit c7ee9ab
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
22 changes: 12 additions & 10 deletions src/Relationships/HasMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public function remove($entity): ?IEntity
return null;
}

$entity = $this->createEntity($entity);
$entity = $this->createEntity($entity, attach: false);
if ($entity === null) {
return null;
}
Expand All @@ -193,7 +193,7 @@ public function remove($entity): ?IEntity

public function has($entity): bool
{
$entity = $this->createEntity($entity, false);
$entity = $this->createEntity($entity, need: false, attach: false);
if ($entity === null) {
return false;
}
Expand Down Expand Up @@ -332,16 +332,18 @@ function (): array {
* @param E|string|int $entity
* @return E|null
*/
protected function createEntity($entity, bool $need = true): ?IEntity
protected function createEntity($entity, bool $need = true, bool $attach = true): ?IEntity
{
if ($entity instanceof IEntity) {
if ($entity->isAttached()) {
$repository = $entity->getRepository()->getModel()->getRepositoryForEntity($this->parent);
$repository->attach($this->parent);

} elseif ($this->parent->isAttached()) {
$repository = $this->parent->getRepository()->getModel()->getRepositoryForEntity($entity);
$repository->attach($entity);
if ($attach) {
if ($entity->isAttached()) {
$repository = $entity->getRepository()->getModel()->getRepositoryForEntity($this->parent);
$repository->attach($this->parent);

} elseif ($this->parent->isAttached()) {
$repository = $this->parent->getRepository()->getModel()->getRepositoryForEntity($entity);
$repository->attach($entity);
}
}

return $entity;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ require_once __DIR__ . '/../../../bootstrap.php';

class RelationshipsOneHasManyHasTest extends DataTestCase
{

public function testHasValue(): void
{
$author = $this->orm->authors->getByIdChecked(1);
Expand All @@ -27,8 +26,8 @@ class RelationshipsOneHasManyHasTest extends DataTestCase
Assert::true($author->books->has($book));
$this->orm->books->remove($book);
Assert::false($author->books->has($book));
Assert::false($book->isAttached());
}

}


Expand Down

0 comments on commit c7ee9ab

Please sign in to comment.