Symfony2 - Doctrine ArrayCollection方法返回未定义 [英] Symfony2 - Doctrine ArrayCollection methods coming back as undefined
问题描述
命名空间Acme\MyBundle\Entity;代码(名称由于NDA而略有变化)
使用Doctrine\ORM\Mapping作为ORM;
使用Doctrine\Common\Collections\ArrayCollection;
// ...
public function setThing($ thing)
{
$ this-> things-> add($ thing );
}
public function getThing()
{
return $ this-> things-> current();
}
真正奇怪的是,它在中抛出异常current()
而不是 add()
:
FatalErrorException:错误:调用未定义的方法Acme\MyBundle\Entity\Thing :: current()in / home / kevin / www / project / vendor / acme / my-bundle / Acme / MyBundle / Entity / MyEntity。 php line 106
根据错误判断,它看起来不是处理的东西
作为ArrayCollection。有没有办法强制的东西
成为一个ArrayCollection?我已经有以下内容:
/ **
* @var ArrayCollection东西
*
* @ ORM\OneToMany(targetEntity =Thing,mappedBy =other)
* /
private $ things;
但我不知道还有什么要做。
奇怪。我可以通过检查它的底层类型来解决它:
public function getThing()
{
if(get_type($ this-> things)==='ArrayCollection'){
return $ this-> things-> current();
} else {
return $ this-> things;
}
}
表单现在正确显示,没有例外。
如果有多个相关实体,也可以分配一个ArrayCollection,如果只有一个实体,则将它留作相关实体? :耸肩:
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.
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:
这篇关于Symfony2 - Doctrine ArrayCollection方法返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!