Doctrine 2 ManyToMany cascade

一笑奈何 提交于 2019-12-18 03:54:46

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/5033825/doctrine-2-manytomany-cascade

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!