我正在尝试在Team实体中创建一条新记录,其中现有用户为User's Entity的所有者,但在使用persist后,它会创建一个新用户,而不是将其附加到记录中。
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;
这是转储记录的样子:
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 ▶}
}
因为你可以看到用户在持久化之前有ID并且被识别但是在持久化之后它会在数据库中创建一个新用户。
请提供一些好建议。
答案 0 :(得分:0)
您需要从实体获取用户对象,以便教学可以将您的团队实体与此用户相关联,现在您从中获取用户对象,我认为安全上下文不是创建新用户的学说对象的原因。< / p>
这应该更改为
$user = $this->getUser();
$user = $em->getRepository('AppBundle\Entity\SteamUser')
->find($this->getUser()->getId());