问题描述
是否可以在 Doctrine 2 中创建两个多对多相关的对象并仅对其中一个调用 persist 来保存两者?
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?
用户实体:
/**
* 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;
角色实体:
/**
* Inverse Side
*
* @ManyToMany(targetEntity="User", mappedBy="roles")
*/
public $users;
保存:
$role = new Role();
$user = new User();
$user->roles->add($role);
$role->users->add($user);
$em->persist($user);
$em->flush();
它不起作用并抛出错误通过未配置为级联持久操作的关系找到了新实体:EntitiesRole@0000000004a29c11000000005c48cb75.显式持久化新实体或在关系上配置级联持久化操作."
It doesn't work and trows an error "A new entity was found through a relationship that was not configured to cascade persist operations: EntitiesRole@0000000004a29c11000000005c48cb75. Explicitly persist the new entity or configure cascading persist operations on the relationship."
推荐答案
您应该将 cascade={"persist"}
应用于 Role 实体.
You should apply cascade={"persist"}
to the Role entity.
不是 Doctrine 的专家,但我认为 Doctrine 会检查关联实体的级联选项.
Not an expert on Doctrine, but I think Doctrine checks the associated entity for cascading options.
由于您将持久化from Users 角色,它会检查角色 实体,如果它应该用级联持久化.
Since you are cascading the persist from Users to Roles, it checks the Role entity if it should be persisted with cascade.
这篇关于学说 2 多对多级联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!