两个引用一个文档


Two reference to one Document

如何对一个文档进行两个引用?

我试一试:

/**
 * @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
}

接下来是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');
}
第二:

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');
}

为什么count($category->getPosts2())返回0 ?为什么这个引用不起作用?在数据库中,此参考(Posts2)与参考Posts相同。

可以使用对象克隆,而不是创建两个引用。请参考php手册- http://php.net/manual/en/language.oop5.cloning.php

您还需要像这样调用flush():

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

那可能是问题所在,但我不确定。每次持久化时都需要刷新。