Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 434
Gopi Kalyan Avatar asked Dec 04 '25 19:12

Gopi Kalyan


1 Answers

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

like image 88
Jovan Perovic Avatar answered Dec 07 '25 09:12

Jovan Perovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!