【问题标题】:Doctrine2 cascade entity creationDoctrine2 级联实体创建
【发布时间】:2015-11-22 15:53:03
【问题描述】:

我有两个实体 User 和 UserProfile。 UserProfile primaryKey 值不是 AUTO_INCREMENT,它是使用来自用户的主键值的一对一关系。当我创建新用户时出现错误:

App\PublicBundle\Entity\User\UserProfile 类型的实体缺少为字段“用户”分配的 ID。此实体的标识符生成策略要求在调用 EntityManager#persist() 之前填充 ID 字段。如果您想要自动生成标识符,则需要相应地调整元数据映射。

问题是如何用下一个数据库和实体结构保存实体:

用户 DDL:

CREATE TABLE `user` (
  `intUserID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`intUserID`),
)
CREATE TABLE `user_profile` (
  `intUserID` int(10) unsigned NOT NULL,
  PRIMARY KEY (`intUserID`),
  CONSTRAINT `user_profile_ibfk_1` FOREIGN KEY (`intUserID`) REFERENCES `user` (`intUserID`) ON DELETE CASCADE ON UPDATE CASCADE
)

用户实体:

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

    /**
     * @var \App\PublicBundle\Entity\User\UserProfile
     *
     * @ORM\OneToOne(targetEntity="\App\PublicBundle\Entity\User\UserProfile",
     *      mappedBy="user",
     *      cascade={"persist", "remove"}
     * )
     */
    protected $profile;
}

用户配置文件实体:

/**
 * @ORM\Table(name="user_profile")
 * @ORM\Entity
 */
class UserProfile
{
    /**
     * @var \App\PublicBundle\Entity\User\User
     *
     * @ORM\Id
     * @ORM\OneToOne(targetEntity="\App\PublicBundle\Entity\User\User",
     *      inversedBy="profile"
     * )
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="intUserID", referencedColumnName="intUserID")
     * })
     */
    protected $user;
}

注册操作

private function registration(Request $request, $tpl)
{
    $user = new User();
    $form = $this->$form($user, 'Create');
    $form->handleRequest($request);

    if ('POST' === $request->getMethod())
    {
        if ($form->isValid())
        {
            $em->getConnection()->beginTransaction();

            try
            {
                $em = $this->getManager();
                $em->persist($user);
                $em->flush();

                $this->sendSuccessEmail($user);
                $em->getConnection()->commit();
            }
            catch (\Exception $e)
            {
                $em->getConnection()->rollback();
                throw $e;
            }

            return $this->redirect($this->generateUrl('app_profile'));
        }
    }

    return $this->render($tpl, array(
        'entity' => $user,
        'form' => $form->createView()
    ));
}

【问题讨论】:

  • 试图保持两个主键同步通常比它的价值更麻烦。特别是在使用诸如 Doctrine 2 之类的对象关系管理器时。只需顺其自然,为您的 UserProfile 提供它自己的数据库 ID。或者使用嵌入的值对象。
  • 是的,我想过,但我想还有另一种更正确的方法

标签: php mysql symfony doctrine-orm


【解决方案1】:

正确的方法,在persist和flush之前设置为null profile,然后再次调用persist和flush:

注册操作

private function registration(Request $request, $tpl)
{
    $user = new User();
    $form = $this->$form($user, 'Create');
    $form->handleRequest($request);

    if ('POST' === $request->getMethod())
    {
        if ($form->isValid())
        {
            $em->getConnection()->beginTransaction();

            try
            {
                $user->setProfile(null);

                $em = $this->getManager();
                $em->persist($user);
                $em->flush();

                $user->setProfile(new UserProfile);
                $user->getProfile()->setUser($user);

                $em = $this->getManager();
                $em->persist($user);
                $em->flush();

                $this->sendSuccessEmail($user);
                $em->getConnection()->commit();
            }
            catch (\Exception $e)
            {
                $em->getConnection()->rollback();
                throw $e;
            }

            return $this->redirect($this->generateUrl('app_profile'));
        }
    }

    return $this->render($tpl, array(
        'entity' => $user,
        'form' => $form->createView()
    ));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2012-05-31
    • 2012-03-03
    • 1970-01-01
    相关资源
    最近更新 更多