简体   繁体   中英

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

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM