在我的Symfony2项目中,我有两个相关实体:用户和收藏夹.他们有多对多的关系.
我的申请工作如下:
在我的Twig页面,我有几个项目,按钮“添加到收藏夹”.当您单击按钮时,我的控制器将item_id保存在收藏夹列中.但是我想要保存
将项目添加到他的收藏夹和我的应用程序的用户失败.
用户和收藏夹存在,但用户和收藏夹之间的连接列保持为空.
我也没有收到任何错误.
这是我的代码:
实体用户
class Users implements AdvancedUserInterface { /** * @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="user_id") * },* inverseJoinColumns={ * @ORM\JoinColumn(name="favorite_id",referencedColumnName="favorite_id") * } * ) */ private $favorite; public function __construct() { $this->favorite = new \Doctrine\Common\Collections\ArrayCollection(); } public function addFavorite(\Geo\CityTroopersBundle\Entity\Favorites $favorite) { $this->favorite[] = $favorite; return $this; } ...
实体收藏
class Favorites { /** * @var \Doctrine\Common\Collections\ArrayCollection * * @ORM\ManyToMany(targetEntity="Users",mappedBy="favorite",cascade={"persist"}) */ private $user; public function __construct() { $this->user = new \Doctrine\Common\Collections\ArrayCollection(); } public function addUser(\Geo\CityTroopersBundle\Entity\Users $user) { $this->user[] = $user; return $this; }
我的控制器
public function showNewsAction() { $request = $this->get('request'); $itemId=$request->request->get('itemId'); if($itemId != NULL) { //MAKE NEW FAVORITE AND ADD TO DATABASE LINKED WITH ITEM $favorite = new Favorites(); $favorite->setItemId($itemId); //LINK FAVORITE ID WITH USER ID IN JOINCOLUMN $userId = 6; $em = $this->getDoctrine()->getEntityManager(); $user = $em->getRepository('GeoCityTroopersBundle:Users')->find($userId); $favorite->addUser($user); $em->persist($favorite); //I TRIED THIS TOO,BUT IT Failed /*$user->addFavorite($favorite); $em->persist($user);*/ $em->flush();