Saving Many to Many relationship to database in Symfony2 Saving Many to Many relationship to database in Symfony2 database database

Saving Many to Many relationship to database in Symfony2


You were close there. For doctrine many-to-many relationships, you need to call both add methods

$favorite->addUser($user);$user->addFavorite($favorite);$em->persist($favorite); $em->persist($user);$em->flush();

This should do the trick. In the docs they do this, but don't mention it too explicitly. Not sure why either because lots of people run into this (myself included).


As explained here, only the owning side is responsible for the connection management :http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#owning-and-inverse-side-on-a-manytomany-association

So only

$user->addFavorite($favorite);

should persist, and not

$favorite->addUser($user);


Like indicated by Cedric, adding a record for a many to many relation is done only in one direction and it depends on how you defined the relation: adding can be done only by the parent entity of the relation, so in your case you must use:

$user->addFavorite($favorite);