在 Symfony2 中保存与数据库的多对多关系 [英] Saving Many to Many relationship to database in Symfony2

查看:23
本文介绍了在 Symfony2 中保存与数据库的多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

In my Symfony2 project I have two related entities: Users and Favorites. They have a many-to-many relationship.

My application works as follows: In my Twig-page I have an few items with a button 'Add to Favorites'. When you click the button my controller saves the item_id in the Favorites column. But then I want to save the user who added the item to his favorites and here my application fails.

The User and the favorite exist but the joincolumn between Users and Favorites remains empty. I also don't receive any kind of errors.

Here is my code:

Entity Users

class Users implements AdvancedUserInterface
{
    /**
     * @var DoctrineCommonCollectionsArrayCollection
     *
     * @ORMManyToMany(targetEntity="Favorites", inversedBy="user", cascade={"persist"})
     * @ORMJoinTable(name="user_has_favorite",
     *   joinColumns={
     *     @ORMJoinColumn(name="user_id", referencedColumnName="user_id")
     *   },
     *   inverseJoinColumns={
     *     @ORMJoinColumn(name="favorite_id", referencedColumnName="favorite_id")
     *   }
     * )
     */
    private $favorite;

    public function __construct()
    {
        $this->favorite = new DoctrineCommonCollectionsArrayCollection();
    }

    public function addFavorite(GeoCityTroopersBundleEntityFavorites $favorite)
    {
        $this->favorite[] = $favorite;

        return $this;
    }
...

Entity Favorites

class Favorites
{

    /**
     * @var DoctrineCommonCollectionsArrayCollection
     *
     * @ORMManyToMany(targetEntity="Users", mappedBy="favorite", cascade={"persist"})
     */
    private $user;

    public function __construct()
    {
        $this->user = new DoctrineCommonCollectionsArrayCollection();
    }
    public function addUser(GeoCityTroopersBundleEntityUsers $user)
    {
        $this->user[] = $user;    
        return $this;
    }

My controller

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

解决方案

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

这篇关于在 Symfony2 中保存与数据库的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆