2017-10-17 125 views
1

我正在使用Symfony 3 Framework與Doctrine和MongoDB。爲什麼我的PersistentCollection爲空?

我有兩個OneToMany關係的文檔。

/** 
* Class Waypoint 
* @package AppBundle\Document 
* @MongoDB\Document(collection="waypoints", repositoryClass="AppBundle\Repository\WaypointRepository") 
*/ 
class Waypoint 
{ 
    /** 
    * @var int 
    * 
    * @MongoDB\Id(strategy="auto") 
    */ 
    private $id; 

    /** 
    * @var ArrayCollection 
    * @MongoDB\ReferenceMany(targetDocument="Comment", cascade={"delete"}) 
    */ 
    private $comments; 

} 

** 
* Class Comment 
* @package AppBundle\Document 
* @MongoDB\Document(collection="comments", repositoryClass="AppBundle\Repository\CommentRepository") 
*/ 
class Comment 
{ 

    /** 
    * @var int 
    * 
    * @MongoDB\Id(strategy="auto") 
    */ 
    private $id; 

    /** 
    * @var Waypoint 
    * 
    * @MongoDB\ReferenceOne(targetDocument="Waypoint", inversedBy="comments") 
    * @Assert\NotBlank() 
    */ 
    private $waypoint; 
} 

現在我從庫中查詢得到我Waypoint項目的一部分,並希望與樹枝來顯示它們。

/** 
* WaypointRepository 
* 
* This class was generated by the Doctrine ORM. Add your own custom 
* repository methods below. 
*/ 
class WaypointRepository extends DocumentRepository 
{ 
    public function getWaypointsForCruiseByPage(Cruise $cruise, $page) 
    { 
     $displayLimit = 10; 
     $amountToSkip = 0; 

     if ($page > 1) 
     { 
      $amountToSkip = ($page -1) * $displayLimit; 
     } 

     $qb = $this->createQueryBuilder() 
      ->select() 
      ->field('cruise')->equals($cruise) 
      ->field('isAutoWaypoint')->equals(false) 
      ->sort('date', -1) 
      ->skip($amountToSkip) 
      ->limit($displayLimit) 
     ; 

     $qb 
      ->addOr($qb->expr()->field('hasImage')->equals(true)) 
      ->addOr($qb->expr()->field('hasAudio')->equals(true)) 
      ->addOr($qb->expr()->field('description')->notEqual('')) 
     ; 

     return $qb->getQuery()->toArray(); 
    } 
} 

現在,我試圖做{{ waypoint.comments.count }}{{ waypoint.comments|length }}將始終爲0,即使我有我的MongoDB中採集數據集。

如果我通過Waypoint的ID獲得CommentRepository的評論,我會得到預期的結果。

// returns the expected results 
public function getAllCommentsForWaypoint(Waypoint $waypoint) 
{ 
    return $this->createQueryBuilder() 
     ->select() 
     ->field('waypoint')->equals($waypoint) 
     ->getQuery()->toArray() 
    ; 
} 

就我所知,映射沒有問題,沒有缺陷或錯誤。

爲什麼PersistentCollection是空的事件,儘管信息在集合中存在?

+0

「現在我從庫中查詢得到我的航點條目的一部分」 - 請貼中提到的查詢 – malarzm

+0

@malarzm我編輯了這個問題 – KhorneHoly

回答

1

我不知道你是如何創建的文檔,但是這是我最好的拍攝:

Waypoint::$comments沒有被映射爲反側從而ODM預計引用的列表,可在waypoint.comments領域在數據庫。最有可能的是它不在那裏(即你沒有明確地向Waypoint中的集合添加新的Comment),這就是爲什麼當查詢航點時看到空集合,但在查詢註釋時有結果。鑑於您在Comment映射我想你忘了設置Waypoint::$comments作爲反方有inversedBy="comments"

/** 
* @var ArrayCollection 
* @MongoDB\ReferenceMany(targetDocument="Comment", mappedBy="waypoint") 
*/ 
private $comments; 
+0

是的,我錯過了'mappedBy =「waypoint」'部分因爲它似乎導致了缺失的引用。謝謝,我只需要添加部分,現在它工作正常。 – KhorneHoly