Zend 2:OneToMany 在会话中不起作用

Zend 2: OneToMany doesn't work in session

我正在使用标准的 Zend 身份验证 + 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 为 1

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 对会话中的对象不起作用吗?

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

最好只在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 时出现问题。