OneToOne 实体不会在 Symfony2 中坚持 Doctrine

OneToOne entities won't persist with Doctrine in Symfony2

我在 Symfony 中有用户和学生之间的 OneToOne 关系,其中用户是所有者,当我尝试坚持更改时,双方都没有进行更改,这是我最后的配置:

<?php

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="BackendBundle\Repository\UserRepository")
 */
class User  implements UserInterface, \Serializable
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
    * @ORM\OneToOne(targetEntity="Student", mappedBy="user")
    */
    private $student;

    public function __construct() {
    }


    /**
     * Set student
     *
     * @param \BackendBundle\Entity\Student $student
     *
     * @return User
     */
    public function setStudent(\BackendBundle\Entity\Student $student)
    {
        $this->student = $student;

        return $this;
    }

    /**
     * Get student
     *
     * @return \BackendBundle\Entity\Student
     */
    public function getStudent()
    {
        return $this->student;
    }

}

学生:

<?php

/**
 * Student
 *
 * @ORM\Table(name="Student")
 * @ORM\Entity(repositoryClass="BackendBundle\Repository\StudentRepository")
 */
class Student
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
    * @ORM\OneToOne(targetEntity="User", inversedBy="student")
    * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
    */
    private $user;

    public function __construct() {

    }
}

在控制器中:

    public function editAction(Request $request, User $user)
{
    $student = new Student();
    $user->setStudent($student);

    $em = $this->getDoctrine()->getManager();
    $em->persist($student);
    $user->setStudent($student);
    $em->persist($user);
    $em->flush();
    /.../
}

我可以毫无例外地保存实体和更改,但我无法将它们关联起来,例如在视图中,当我执行 {{ user.student }} 时它给我 null,而 {{ student.user_id }} 也是空。

修改你的代码如下

 <?php

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="BackendBundle\Repository\UserRepository")
 */
class User  implements UserInterface, \Serializable
{
    /**
    * @ORM\OneToOne(targetEntity="Student", mappedBy="user", cascade={"persist"})
    */
    private $student;

    // ...

    /**
     * Set student
     *
     * @param \BackendBundle\Entity\Student $student
     *
     * @return User
     */
    public function setStudent(\BackendBundle\Entity\Student $student)
    {
        $this->student = $student;
        $student->setUser($this);

        return $this;
    }

    // ...
}

public function editAction(Request $request, User $user)
{
    $student = new Student();
    $user->setStudent($student);

    $em->flush();
}

为什么要编辑?

因为学说 "listen" 仅适用于更改为拥有方(因此 Student 实体)。如果你想坚持用户而不让学生头疼,你需要:

1 - 将学生设置为用户时将用户设置为学生(拥有方)
2 - 对用户

的学生 属性 使用级联持久化

PS.: 如果您使用原则(甚至使用参数转换器)从数据库中检索用户(更一般地说是一个实体),则不需要显式调用 persist 到该实体。