我在db中创建了两个条目:
$new_user = new User();
$em->persist($new_user);
$new_friends = new UserFriends ();
$new_friends->setUserId($new_user);
UserFriends-Entity的一部分:
/**
* @var \User
*
* @ORM\ManyToOne(targetEntity="User")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
* })
*/
private $user_id;
如何从新User()获取id以创建新条目new UserFriends()?
现在我做
$em->persist($new_user); $em->flush();
$id = $em->.....getRepository('Entity:User')->find($id);
$new_friends = new UserFriends ();
$new_friends->setId($id);
$em->persist($new_friends); $em->flush();
有更好的方法吗?而不是对数据库做另一个请求?在学说1.2中,这很容易。
答案 0 :(得分:0)
致电$em->flush();
后,调用$new_user->getId();
应返回新插入的ID。所以
$em->persist($new_user);
$em->flush();
$new_friends = new UserFriends ();
$new_friends->setId($new_user->getId());
$em->persist($new_friends);
$em->flush();