Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

php - Doctrine 2 ManyToMany cascade

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: EntitiesRole@0000000004a29c11000000005c48cb75. Explicitly persist the new entity or configure cascading persist operations on the relationship."

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...