在我的 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();