duanliaouu965826 2017-10-05 18:49
浏览 151

Symfony 3 ORM在持久化后创建新的实体记录

i'm trying to create a new record in Team entity with existing user as owner from User's Entity but after using persist it creates a new user rather than attaching it to record.

    public function createTeam(Request $request)
    {
        $teamForm = $this->createForm(TeamType::class);

        $teamForm->handleRequest($request);
        if ($teamForm->isSubmitted() && $teamForm->isValid()) {

            $user = $this->getUser();
            $team = $teamForm->getData();

            $team->setCreatedAt(new \DateTime())
                 ->setCreator($user);

            $this->em->persist($team);
    //dd($team);
            $this->em->flush();

        }

ORM:

        /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\SteamUser", cascade={"persist"})
     * @ORM\JoinColumn(name="steam_user_id", referencedColumnName="id", onDelete="SET NULL")
     */
    private $creator;

Here is what dump record looks like:

    TeamController.php on line 52:
Team {#591 ▼
  -id: null
  -creator: SteamUser {#238 ▼
    -id: 1
    -roles: array:1 [▶]
    -nickName: "steamuser"
    -userName: "76561192288153971"
    -password: "LrC8fFLuIdPqAiDHDATiheRaIBk="
    -avatar: "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9e/9e8567cc32383f28df41da7fbca7e8afd47f8516.jpg"
    -teams: PersistentCollection {#290 ▶}
  }
  -name: "dasdasdasdas"
  -logo: null
  -teamType: 2
  -createdAt: DateTime {#594 ▶}
  -roster: ArrayCollection {#571 ▶}
}

as you can see user before persist has ID and is recognized but after persist it creates a new user in database.

Please give some good advices.

  • 写回答

1条回答 默认 最新

  • douyi3676 2017-10-07 10:56
    关注

    You need to get the user object from entity so that doctrine can relate your team entity to this user right now you are getting user object from i guess security context which is not a doctrine object that is why new user is created.

    this should be changed as below $user = $this->getUser();

    $user = $em->getRepository('AppBundle\Entity\SteamUser')
               ->find($this->getUser()->getId());
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题