Saving Many to Many relationship to database in Symfony2

只愿长相守 提交于 2019-12-03 05:54:02
Squazic

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);

In your line :

@ORM\JoinColumn(name="favorite_id", referencedColumnName="favorite_id")

The

name="favorite_id"

part refers to the columns in the join table, whereas the

referencedColumnName="favorite_id"

refers to the id in the favorite table which usualy is simply "id". You should try :

    /**
 * @var \Doctrine\Common\Collections\ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="Favorites", inversedBy="user", cascade={"persist"})
 * @ORM\JoinTable(name="user_has_favorite",
 *   joinColumns={
 *     @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 *   },
 *   inverseJoinColumns={
 *     @ORM\JoinColumn(name="favorite_id", referencedColumnName="id")
 *   }
 * )
 */
private $favorite;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!