Search code examples
mongodbdoctrine-odmodm

Doctrine Mongo ODM reference 3 collections


Hi I'm trying to reference 3 collections but i fail fom 2 > 3 referencing, let me explain what i'm trying to do.

I have User class that have reference posts referenceMany > Posts and in posts i have referenceMany > comments.

Note: Doctrine Mongo ODM + Zend Framework 2

It's something like user write a post and someone comment on it.

/** @MongoDB\Document */
class Users {

    /** @MongoDB\ReferenceMany(targetDocument="Posts", mappedBy="user") */
    private $posts;

}

/** @MongoDB\Document */
class Posts {

    /** @MongoDB\Id */
    private $wallPostId;

    /** @MongoDB\ReferenceOne(targetDocument="Users", inversedBy="posts") */
    private $user;

    /** @MongoDB\ReferenceMany(targetDocument="Comments", mappedBy="post") */
    private $comments;

    /** @MongoDB\String */
    private $content;

}

/** @MongoDB\Document */
class Comments {

    /** @MongoDB\Id */
    private $commentId;

    /** @MongoDB\ReferenceOne(targetDocument="Posts", inversedBy="comments") */
    private $post;

    /** @MongoDB\String */
    private $content;

}

I'm trying this code to get all comments from any post

$post = $wallPostsAction->getWallPostById("5051d2a1e71a382c1b000000");
$output = "";
$output .= "Wall post content: " . $post->getContent() . "<br>";
//      $comment = new Comments();
//      $comment->setContent("Nice topic!");
//      $comment->setPost($post);
//      $this->dm->persist($comment);
//      $this->dm->flush();

echo count($post->getComments());
foreach($post->getComments() as $comment){
    $output .= " comment: " . $comment->getComment() . "<br>";
}

one of the document look like this for comment:

{
   "_id": ObjectId("---"),
   "post"?: {
     "$ref": "Posts",
     "$id": ObjectId("---"),
     "$db": "db" 
  },
   "content": "Nice topic!" 
}

Question is why i get 0 count for comment when i try to get them for specific post but when i try to get posts from user i can get them.


Solution

  • Because all that getComments() returns is a cursor to that collection. Doctrine won't run any queries to obtain the information until you start to iterate over that collection.

    Add this to the query in your getWallPostById method.

    ->field('comments')->prime(true)
    

    This will tell doctrine to fetch the data about the comments when you fetch a post and then your cursor from getComments should have the count information you are looking for.

    Priming references