致命错误:调用未定义的方法Doctrine \ ORM \ PersistentCollection :: getPath()
用户实体: user.php的
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity
* @ORM\Table(name="users")
*/
class User implements UserInterface, \Serializable
{
/**
* @ORM\OneToMany(targetEntity="Avatars", mappedBy="user")
*/
protected $avatars;
/**
* @return mixed
*/
public function getAvatar()
{
return $this->avatars;
}
public function __construct()
{
$this->avatars = new ArrayCollection();
}
/**
* Get avatars
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAvatars()
{
return $this->avatars;
}
和阿凡达实体: Avatar.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="avatars")
*/
class Avatars
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="avatars")
* @ORM\JoinColumn(name="user", referencedColumnName="id")
*/
private $user;
/**
* @ORM\Column(type="string", length=54)
*/
private $path;
/**
* @return mixed
*/
public function getPath()
{
return $this->path;
}
无法从控制器访问“头像实体”:
HomeController.php
public function homeAction()
{
$usr= $this->get('security.token_storage')->getToken()->getUser();
var_dump($user->getAvatar()->getPath());exit;
}
我错在哪里?我只是开始学习symfony框架,也许我忘了添加任何东西?
答案 0 :(得分:3)
您User
实体包含Avatar
个对象的集合,而不仅仅是一个对象。例如,您可以做的是迭代化身并在每个单个对象上调用getPath()
,如下所示:
foreach ($user->getAvatar() as $avatar) {
var_dump($avatar->getPath();
}
顺便说一下,getAvatar()
类中代码中的方法名称User
会产生误导,因为人们会期望用户只有一个头像,而不是一个头像集合。我会将其重命名为getAvatars()
。