Gopi Kalyan
Gopi Kalyan

Reputation: 129

Deleting object part of a Many-to-Many relationship with EntityManager returns error

I have a schema with a Many-to-Many relationship between entities "User" and "Role" mapped as follows.

Role entity

/**
 * @ORM\ManyToMany(targetEntity="User", mappedBy="roles", cascade={"persist", "remove"})
 */
protected $users;

and the User entity

/**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist", "remove"})
 * @ORM\JoinTable(name="users_roles")
 * 
 * @var ArrayCollection $userRoles
 */
protected $userRoles;

When I try to delete a role object with the following code,

$role = $em->getRepository('ACMEDefaultBundle:Role')->find($id);
$em->remove($role);
$em->flush();

I am getting a Doctrine Exception

ErrorException: Notice: Undefined index: roles in /media/sf_sandbox/aalcodev/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 964 (uncaught exception) at /media/sf_sandbox/aalcodev/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 964

Please help. Thank you.

Upvotes: 3

Views: 274

Answers (1)

Jovan Perovic
Jovan Perovic

Reputation: 20193

You should change mappedBy="roles" to mappedBy="userRoles". "Mapped by" should point to other side's property name...

Upvotes: 3

Related Questions