2016-10-12 2 views
1

Как я могу сделать две ссылки на один документ?Две ссылки на один документ

Стараюсь:

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

А затем в контроллер, первый:

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

Вы также должны позвонить flush() так:

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

Это может быть проблемой, но я не уверен. Вам нужно стирать каждый раз, когда вы упорствуете.

Смежные вопросы