php 学说 2 多对多级联

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5033825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:35:48  来源:igfitidea点击:

Doctrine 2 ManyToMany cascade

phpormdoctrine

提问by awattar

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?

是否可以在 Doctrine 2 中创建两个多对多相关的对象,并仅在其中一个上调用 persist 来保存两者?

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."

它不起作用并引发错误“通过未配置为级联持久操作的关系找到新实体:Entities\Role@0000000004a29c11000000005c48cb75。显式持久化新实体或在关系上配置级联持久化操作。”

回答by Hakan Deryal

You should apply cascade={"persist"}to the Role entity.

您应该申请cascade={"persist"}Role 实体。

Not an expert on Doctrine, but I think Doctrine checks the associated entity for cascading options.

不是 Doctrine 的专家,但我认为 Doctrine 检查关联实体的级联选项。

Since you are cascading the persist fromUserstoRoles, it checks the Roleentity if it should be persisted with cascade.

由于您将持久化Users级联Roles,它会检查Role实体是否应该使用级联持久化。