无法获取用户的头像实体以在 Symfony2 中将其删除

Can't get User's Avatar entity to remove it in Symfony2

我有一个用户实体和一个具有一对一关系的头像实体:

//MyBundle/Entity/User.php

/**
 * @ORM\OneToOne(targetEntity="Participso\UserBundle\Entity\Avatar", cascade={"remove", "persist"})
 */
protected $avatar;

如果用户已经有头像,我想用这个删除之前的头像:

//MyBundle/Controller/UserController.php

if ($avatarForm->isValid()) {
    $em = $this->getDoctrine()->getManager();

    if($currentUser->getAvatar()){
        $em->remove($currentUser->getAvatar());
    }

    $currentUser->setAvatar($avatar);
    $em->persist($currentUser); //"cascade=persist" from User
    $em->flush();
}

还有这个:

//MyBundle/Entity/Avatar.php

/**
 * @ORM\PostRemove()
 */
public function removeUpload()
{
    $file = __DIR__.'/../../../../web/uploads/avatar/' . $this->fileName;
    unlink($file);
}

但是当我这样做时 var_dump($currentUser->getAvatar()) 我得到一个空文件名,即使文件名存在于数据库中:

object(Proxies\__CG__\Participso\UserBundle\Entity\Avatar)[355]
    public '__initializer__' => 
object(Closure)[348]
    public '__cloner__' => 
object(Closure)[349]
    public '__isInitialized__' => boolean false
    private 'id' (Participso\UserBundle\Entity\Avatar) => int 20
    public 'file' => null
    private 'fileName' (Participso\UserBundle\Entity\Avatar) => null

当我执行 var_dump($currentUser->getAvatar()->getFileName) 时,我得到了文件名!! (而不是之前看到的 NULL)...

有人知道吗?

试试这个:

if($currentUser->getAvatar()){
       $currentUser->removeUpload();
}

感谢您的回复!

其实是因为"lazy loading"的教义:

如果我这样做:

var_dump($currentUser->getAvatar());exit;

输出:

object(Proxies\__CG__\Participso\UserBundle\Entity\Avatar)[355]
    private 'id' (Participso\UserBundle\Entity\Avatar) => int 20
    private 'fileName' (Participso\UserBundle\Entity\Avatar) => null

但如果我这样做

$whatever = $currentUser->getAvatar()->getFileName();
var_dump($currentUser->getAvatar());exit;

输出:

object(Proxies\__CG__\Participso\UserBundle\Entity\Avatar)[355]
    private 'id' (Participso\UserBundle\Entity\Avatar) => int 20
    private 'fileName' (Participso\UserBundle\Entity\Avatar) => string 'd4e5eadd3757498a22b14ad1f81869c2baf459d3.png'

这很烦人...我将创建一个新的 post 来解决这个问题。

编辑: 新的 post 是 ,并且已解决:

为了避免从学说中延迟加载,只需在您的父实体中添加 fetch="EAGER" :

/**
 * @OneToOne(targetEntity="User")
 * @JoinColumn(name="user_id", referencedColumnName="id", fetch="EAGER")
 */