[英]Symfony - persisting ManyToMany relation
Is there any other way I could write this bit of code better? 还有其他方法可以更好地编写这段代码吗? Am I missing something here?
我在这里想念什么吗?
$user->addEntity($entity);
$entity->addUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->persist($entity);
You can add only from the owning side of the relation; 您只能从关系的拥有方进行添加; then you can
persist
only that object and flush it. 那么您只能
persist
该对象并将其刷新。
For example, if your annotations are like this 例如,如果您的注释是这样的
class User
{
/**
* @ORM\ManyToMany(targetEntity="Entity", inversedBy="users")
* @ORM\JoinTable(name="user_entity")
*/
protected $entities
}
class Entity
{
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="entities")
*/
protected $users;
}
you can do this 你可以这样做
$user->add($entity);
$em = $this->getDoctrine()->getManager();
$em->flush();
You can skip persist
if $user
is fetched from db and if it's not a new object. 如果从数据库中获取了
$user
并且它不是一个新对象,则可以跳过persist
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.