collections icon indicating copy to clipboard operation
collections copied to clipboard

Add merge method to ArrayCollection

Open dozsan opened this issue 10 months ago • 2 comments

Feature Request

The ArrayCollection-on class should have a merge method

Why

When I want to add ManyToMany items, the doctrine deletes them first and then adds them, but this can be used to prevent it from deleting what we don't want to delete

How

public function merge(Collection $collection): self
    {
        foreach ($this->getValues() as $element) {
            if (!$collection->contains($element)) {
                $this->removeElement($element);
            }
        }

        foreach ($collection as $element) {
            if (!$this->contains($element)) {
                $this->add($element);
            }
        }

        return $this;
    }

dozsan avatar Mar 10 '25 21:03 dozsan

This should be opened on doctrine/collections instead

garak avatar Mar 28 '25 19:03 garak

I made my suggestion for this in the PR https://github.com/doctrine/collections/pull/462

demotuulia avatar Apr 23 '25 06:04 demotuulia

The ArrayCollection is just the default implementation of the collection contracts. I don't believe that we need functionality to that class that is not supported by any other collection.

Also, would this merge function do anything beyond the following?

return new ArrayCollection(array_merge(
    $collectionA->toArray(),
    $collectionB->toArray(),
));

If not, I'd like to close this issue.

derrabus avatar Aug 17 '25 22:08 derrabus

Closing as explained.

derrabus avatar Oct 06 '25 17:10 derrabus