Doctrine2 ArrayCollection

Posted by boosis on Stack Overflow See other posts from Stack Overflow or by boosis
Published on 2011-01-29T22:56:55Z Indexed on 2011/02/14 23:25 UTC
Read the original article Hit count: 389

Ok, I have a User entity as follows

<?php
class User 
{
    /**
     * @var integer
     * @Id
     * @Column(type="integer")
     * @GeneratedValue
     */
    protected $id;
    /**
     * @var \Application\Entity\Url[]
     * @OneToMany(targetEntity="Url", mappedBy="user", cascade={"persist", "remove"})
     */
    protected $urls;
    public function __construct()
    {
        $this->urls = new \Doctrine\Common\Collections\ArrayCollection();
    }
    public function addUrl($url)
    {
       // This is where I have a problem
    }
}

Now, what I want to do is check if the User has already the $url in the $urls ArrayCollection before persisting the $url.

Now some of the examples I found says we should do something like

if (!$this->getUrls()->contains($url)) {
    // add url
}

but this doesn't work as this compares the element values. As the $url doesn't have id value yet, this will always fail and $url will be dublicated.

So I'd really appreciate if someone could explain how I can add an element to the ArrayCollection without persisting it and avoiding the duplication?

Edit

I have managed to achive this via

$p = function ($key, $element) use ($url) 
{ 
    if ($element->getUrlHash() == $url->getUrlHash()) { 
        return true; 
    } else { 
        return false; 
    } 
};

But doesn't this still load all urls and then performs the check? I don't think this is efficient as there might be thousands of urls per user.

© Stack Overflow or respective owner

Related posts about lazy-loading

Related posts about doctrine2