如何对一个文档进行两次引用?
我试试:
/**
* @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中,首先:
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)与参考帖子相同。
答案 0 :(得分:0)
您可以使用对象克隆,而不是创建两个引用。请参阅php手册 - http://php.net/manual/en/language.oop5.cloning.php
答案 1 :(得分:0)
您还需要像这样致电flush()
:
$dm->persist($c);
$dm->flush();
这可能是问题所在,但我不确定。 每次坚持都需要冲洗。