问题
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