php - Doctrine2 级联实体创建

标签 php mysql symfony doctrine-orm

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

Entity of type App\PublicBundle\Entity\User\UserProfile is missing an assigned ID for field 'user'. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.

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

用户 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;
}

注册 Action

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()
    ));
}

最佳答案

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

注册 Action

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()
    ));
}

关于php - Doctrine2 级联实体创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856782/

相关文章:

php - 如何均衡64位到32位整数的值

php - 用php写sql

mysql - 将mysql子查询转换为join

更新后的 MySQL 触发器 - 如果列不为空则更新

symfony - 如何在多个实体管理器中使用 Symfony Autowiring

javascript - 通过 AJAX 发送 JS 数组到 laravel 不起作用

php - 在 MySQL 中存储逗号分隔的数据

php - 在 mysql 中使用 IF 语句选择更新

symfony - 如何在 symfony 2 中验证奏鸣曲媒体类型

多语言站点的 Symfony2 URL 翻译和结构