Skip to content

Optimize/simplify generated "remove" method for Doctrine oneToMany relations? #673

@dmaicher

Description

@dmaicher

Currently for a oneToMany Doctrine relation this method is generated on an Entity to remove an element of the collection:

public function removeItem(Item $item): self
{
    if ($this->items->contains($item)) {
        $this->items->removeElement($item);
        // set the owning side to null (unless already changed)
        if ($item->getRelatedThing() === $this) {
            $item->setRelatedThing(null);
        }
    }

    return $this;
}

We don't really need to test first if the element is contained inside the collection. The return value of removeElement can be used instead.

So I suggest to just generate code like this:

public function removeItem(Item $item): self
{
    if ($this->items->removeElement($item)) {
        // set the owning side to null (unless already changed)
        if ($item->getRelatedThing() === $this) {
            $item->setRelatedThing(null);
        }
    }

    return $this;
}

or

public function removeItem(Item $item): self
{
    if ($this->items->removeElement($item)
        // set the owning side to null (unless already changed)
        && $item->getRelatedThing() === $this
    ) {
        $item->setRelatedThing(null);
    }

    return $this;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions