Zend 2:OneToMany在会话中没有工作

时间:2015-10-19 11:57:17

标签: php doctrine-orm zend-framework2

我使用标准的Zend Authentication + Doctrine 2,当用户登录并且他的凭据有效时,我将数据存储在会话中,但我注意到当我检索用户身份时,我无法从OneToMany获取数据关系。

user.php的

/**
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class User
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    // email and password variables

    /**
     * @var \Application\Entity\Profile
     *
     * @ORM\OneToMany(targetEntity="Application\Entity\Profile", mappedBy="assignedToUser")
     */
     protected $createdProfiles;
}

Profile.php

/**
 * @ORM\Table(name="profiles")
 * @ORM\Entity
 */
class Profile
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    // name, status + other irrelevant fields

    /**
     * @ORM\ManyToOne(targetEntity="Application\Entity\User", inversedBy="createdProfiles")
     * @ORM\JoinColumn(name="assigned_to_user", referencedColumnName="id")
    **/
     private $assignedToUser;
}

现在,当我尝试登录时,请说明用户的帐号ID

use Zend\Authentication\AuthenticationService;

$auth = new AuthenticationService();
$authAdapter = new Adapter($username, $password);

$result = $auth->authenticate($authAdapter);

if ($result->isValid()) {
    foreach ($auth->getIdentity()->getcreatedProfiles() as $profile) {
        var_dump($profile->getName()) //                             works fine
    }
}

但是当我采取其他行动时:

public function myAction()
{
    $user = $this->identity()->getFirstName(); //                  works
    foreach ($this->identity()->getCreatedProfiles() as $profile) {
        var_dump($profile->getName()) //                           ! DOESN'T WORK !
    }

    $user = $em->getRepository('Application\Entity\User')->find(1);

    $name = $user->getFirstName(); //                              works
    foreach ($user->getCreatedProfiles() as $profile) {
        var_dump($profile->getName()) //                           ! WORKS FINE !
    }
}

我尝试添加cascade="refresh",但看起来并没有这样做。

知道为什么关系OneToMany不会在会话中处理对象?

1 个答案:

答案 0 :(得分:0)

保存到会话中的实体不再在下一个请求中进行管理。阅读the documentation on how to handle entities in the session

最好只在会话中保存用户ID,并使用标识符解析实体:

$id = $this->identity();
$user = $entityManager->find(User::class, $id);

最重要的是,我在您的实体定义中看到了一个问题。您需要始终initialize your collections in the constructor。因此,请添加到User实体:

public function __construct()
{
    $createdProfiles = new ArrayCollection();
}

在尝试getCreatedProfiles时,忘记这一点也会导致问题。