Search code examples
mongodbsymfonydoctrine-ormsymfony-2.1doctrine-mongodb

findBy reference doctrine-mongodb


I have collections of users and posts.

User looks like

{ "_id" : ObjectId("5089cc4c7b03b9902b000000"), "facebook_id" : "522128874" }

Post looks like

{ "_id" : ObjectId("508aa21b7b03b9780800000f"), "facebook_id" : "10150709375878875", "user" : DBRef("User", ObjectId("5089cc4c7b03b9902b000000")), "message" : " Julia dream, dreamboat queen, queen of all my dreams", "updated_time" : 1333502938 }

I want to find all the posts of a specific user.

$user = $userRepo->findOneByFacebookId('522128874');
$posts = $postRepo->findOneByUser($user)

It doesn't work. I've also tried

$posts = $postRepo->findOneBy(array('user' => $user))

and

$posts = $postRepo->findOneBy(array('user' => $user->getId()))

Solution

  • If you mapped your document relationships correctly, all you would need to do is just

    $user = $userRepo->findOneByFacebookId($fbid);
    $posts = $user->getPosts();
    

    You might want to look at Bidirectional References Doctrine Documentation

    If you want to find the posts of the user manually (the more tedious way), you have to create the method called findOneByUser($user) inside your Post repository. Then you will have to convert user ID to to a MongoId then use querybuilder to match user.$id field to the MongoId which will return cursor(s).

    Remember, when you create a document (post in this case) that has reference to another document, it stores the reference via its MongoId, so you cannot simply just do findOneByUser($user) unless you have created this method yourself.