Vahe Hovhannisyan
Vahe Hovhannisyan

Reputation: 480

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()))

Upvotes: 1

Views: 7219

Answers (3)

Simone Dagli Orti
Simone Dagli Orti

Reputation: 476

You must use the references() method of Query Builder for a @ReferenceOne like https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html

$qb = $postRepo->createQueryBuilder('u')
               ->field('user')->references($user);


PS: use includesReferenceTo() a @ReferenceMany

Upvotes: 0

jeremy
jeremy

Reputation: 71

Bam!

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

Try that, worked for me. Would seem kinda stupid that you would have to query all elements.

Upvotes: 7

Hyunmin Kim
Hyunmin Kim

Reputation: 971

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.

Upvotes: 2

Related Questions