主义2 ManyToMany级联 [英] Doctrine 2 ManyToMany cascade
问题描述
用户实体:
可以在Doctrine 2中创建两个很多对象的对象, / p>
/ **
*拥有端
*
* @ManyToMany(targetEntity =角色,inversedBy =users,cascade = {persist})
* @JoinTable(name =user_roles,
* joinColumns = {@ JoinColumn(name =user_id,referencedColumnName = id)},
* inverseJoinColumns = {@ JoinColumn(name =role_id,referencedColumnName =id)}
*)
* /
public $ roles;
角色实体:
/ **
*反面
*
* @ManyToMany(targetEntity =User,mappedBy =roles)
* /
public $用户;
保存:
code> $ role = new Role();
$ user = new User();
$ user-> roles-> add($ role);
$ role-> users-> add($ user);
$ em-> persist($ user);
$ em-> flush();
它不起作用,并且会产生错误通过关系不是一个新的实体配置为级联持久化操作:Entities\Role @ 0000000004a29c11000000005c48cb75。明确地保留新实体或对关系配置级联持久性操作。
您应该将 cascade = {persist}
应用于角色实体。
不是专家原则,但我认为Doctrine检查关联实体的级联选项。
由于您将 用户 到 角色,它会检查角色实体,如果它应该保持级联。
Is it possible in Doctrine 2 to create two objects that are many to many related and call persist only on one of them to save both?
User entity:
/**
* Owning Side
*
* @ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist"})
* @JoinTable(name="user_roles",
* joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
public $roles;
Role entity:
/**
* Inverse Side
*
* @ManyToMany(targetEntity="User", mappedBy="roles")
*/
public $users;
Saving:
$role = new Role();
$user = new User();
$user->roles->add($role);
$role->users->add($user);
$em->persist($user);
$em->flush();
It doesn't work and trows an error "A new entity was found through a relationship that was not configured to cascade persist operations: Entities\Role@0000000004a29c11000000005c48cb75. Explicitly persist the new entity or configure cascading persist operations on the relationship."
You should apply cascade={"persist"}
to the Role entity.
Not an expert on Doctrine, but I think Doctrine checks the associated entity for cascading options.
Since you are cascading the persist from Users to Roles, it checks the Role entity if it should be persisted with cascade.
这篇关于主义2 ManyToMany级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!