Trong dự án Symfony2 của tôi, tôi có hai thực thể liên quan: Người dùng và Yêu thích. Họ có mối quan hệ nhiều-nhiều.Lưu nhiều mối quan hệ vào cơ sở dữ liệu trong Symfony2
Ứng dụng của tôi hoạt động như sau: Trong trang Twig của tôi, tôi có một vài mục có nút 'Thêm vào mục yêu thích'. Khi bạn nhấn vào nút điều khiển của tôi lưu item_id trong cột Favorites. Nhưng sau đó tôi muốn lưu người dùng đã thêm mục vào mục yêu thích của mình và tại đây ứng dụng của tôi không thành công.
Người dùng và người yêu thích tồn tại nhưng phần kết hợp giữa Người dùng và Ưa thích vẫn trống. Tôi cũng không nhận được bất kỳ loại lỗi nào.
Đây là mã của tôi:
Người dùng Entity
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;
}
...
Entity Favorites
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;
}
điều khiển của tôi
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();
Không thành công ...? Bạn đã nhận được một lỗi hoặc nó không làm các trick? Nếu bạn có lỗi, hãy đăng nó. – Pierrickouw