1

How can I make two reference to one Document?

I try:

/**
 * @MongoDB\Document
 */
class Category
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\ReferenceMany(targetDocument="Post", mappedBy="category")
     */
    private $posts = array();

    /**
     * @MongoDB\ReferenceMany(targetDocument="Post", mappedBy="category2")
     */
    private $posts2 = array();

    /**
     * @MongoDB\Field(type="string")
     */
    protected $name;
    public function __construct()
    {
        $this->posts = new \Doctrine\Common\Collections\ArrayCollection();
        $this->posts2 = new \Doctrine\Common\Collections\ArrayCollection();
    }

//getters and setters
}



/**
 * @MongoDB\Document
 */
class Post
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     * @MongoDB\ReferenceOne(targetDocument="Category", inversedBy="posts")
     * @MongoDB\Index
     */
    protected $category;

    /**
     * @MongoDB\ReferenceOne(targetDocument="Category", inversedBy="posts2")
     * @MongoDB\Index
     */
    protected $category2;

    /**
     * @MongoDB\Field(type="string")
     */
    protected $title;

//getters and setters
}

And next in Controller, first:

public function testAction()
{
    $dm = $this->get('doctrine_mongodb')->getManager();

   $c = new \AppBundle\Document\Category();
   $c->setName('aaa');

   $dm->persist($c);

   $c2 = new \AppBundle\Document\Category();
   $c2->setName('bbb');

   $dm->persist($c2);

   $p = new \AppBundle\Document\Post();
   $p->setCategory($c);
   $p->setCategory2($c2);
   $p->setTitle('sss');

   $dm->persist($p);

   $p = new \AppBundle\Document\Post();
   $p->setCategory($c);
   $p->setCategory2($c2);
   $p->setTitle('ddd');

   $dm->persist($p);

   $dm->flush();

   return new Response('1');
}

Second:

public function test2Action()
    {
       $repository = $this->get('doctrine_mongodb')
                    ->getManager()
                    ->getRepository('AppBundle:Category');

        $category = $repository->findOneBy(array());

        echo count($category->getPosts());  // return 2 - OK
        echo count($category->getPosts2()); // return 0 - ?

       return new Response('1');
}

So why count($category->getPosts2()) return 0 ? Why this reference not working? In database this reference (Posts2) is same as reference Posts.

yakuj
  • 11
  • 2

2 Answers2

0

Instead of creating two references, you can use object clone. Please refer the php manual - http://php.net/manual/en/language.oop5.cloning.php

Manikandan S
  • 902
  • 1
  • 8
  • 18
0

You also need to call flush() like so:

$dm->persist($c);
$dm->flush();

That might be the problem, but I'm not certain. You need to flush each time you persist.

Alvin Bunk
  • 7,621
  • 3
  • 29
  • 45