Symfony2 - Doctrine ArrayCollection methods coming back as undefined

*爱你&永不变心* 提交于 2019-12-11 18:59:33

问题


This is odd. I have an entity that can contain an ArrayCollection of other, related entities. When I make a couple of helper methods to allow me to add/retrieve the value of a singular entity, I get a Symfony2 exception telling me the method is not defined. I'm including the namespace, so I'm at a loss as to what the problem is. Code (names changed slightly due to a NDA) below:

namespace Acme\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

// ...

public function setThing($thing)
{
    $this->things->add($thing);
}

public function getThing()
{
    return $this->things->current();
}

What's really strange is that it's throwing the exception at current() but not add():

FatalErrorException: Error: Call to undefined method Acme\MyBundle\Entity\Thing::current() in /home/kevin/www/project/vendor/acme/my-bundle/Acme/MyBundle/Entity/MyEntity.php line 106

Judging by the error, it looks like it's not treating things as an ArrayCollection. Is there any way to force things to be an ArrayCollection? I already have the following:

/**
 * @var ArrayCollection things
 *
 * @ORM\OneToMany(targetEntity="Thing", mappedBy="other")
 */
private $things;

But I'm not sure what else to do.


回答1:


Odd. I was able to work around it by checking its underlying type:

public function getThing()
{
    if (get_type($this->things) === 'ArrayCollection') {
        return $this->things->current();
    } else {
        return $this->things;
    }
}

The form now appears, correctly, with no exceptions.

Maybe it lazy-assigns an ArrayCollection if there's more than one related entity, and leaves it as just the related entity if there's only one? :shrug:




回答2:


You should initialize ArrayCollection in your entity constructor:

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

otherwise you got null instead ArrayCollection for new entities



来源:https://stackoverflow.com/questions/17051038/symfony2-doctrine-arraycollection-methods-coming-back-as-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!