Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OrphanRemoval does not work with ArrayCollection and manual persist which is not mentioned in the docs #9847

Closed
olsavmic opened this issue Jun 15, 2022 · 0 comments · Fixed by #9848

Comments

@olsavmic
Copy link
Contributor

Bug Report

Q A
BC Break no
Version 2.11.x

Summary

I'd say this issue does not have a simple solution and it just requires documentation change.

Assume we have following entities:

#[Entity]
class Foo
{

    #[OneToMany(mappedBy: "foo", targetEntity: Bar::class, orphanRemoval: true)]
    public Collection $collection;

    public function __construct()
    {
        $this->collection = new ArrayCollection();
    }

}

#[Entity]
class Bar
{

    #[JoinColumn]
    #[ManyToOne(targetEntity: Foo::class, inversedBy: "collection")]
    public Foo $foo;

}

Current behavior

Following code will create an entity even though the collection should be empty:

$foo = new Foo();
$bar = new Bar();

$bar->foo = $foo;
$entityManager->persist($bar);
$foo->collection->add($bar);

$foo->collection->clear();

// Bar will be created in the DB and hydrated on refresh
$entityManager->flush();

The issue is caused by combination of orphanRemoval with manually calling $entityManager->persist($entity) which is hard to fix (as ArrayCollection does not have access to entity manager) yet undocumented so unexpected.

Following code will work as expected:

// Working - Bar will be created & deleted
$foo = new Foo();
$bar = new Bar();

$bar->foo = $foo;
$entityManager->persist($bar);
$foo->collection->add($bar);

// Now the collection becomes PersistentCollection which does propagate changes to UnitOfWork
$entityManager->flush();

$foo->collection->clear();

$entityManager->flush();

Expected behavior

The only possible solution that comes to my mind is to document this behavior in orphanRemoval part and recommend using it alongside cascade=["persist"]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant