Search code examples
symfonydoctrinedoctrine-odmdoctrine-query

How do I query for all items which have a specific item embeded in doctrine odm


I have Comments for something and it's possible to like them. The likes are saved in the Comments as EmbedMany(targetDocument=User).

I want to query for all Comments a Specific User has liked, how do I do that?

I thought of something like:

$dm->createQueryBuilder('Comment')
    ->field('likes.id')
    ->in(array($user->getId()))
    ->getQuery()
    ->execute();

but this doesn't seem to work.


Solution

  • You can query on the embeded document as if it were a normal field. It's type is an ObjectId, though, so you have to manually create the MongoId to query on.

    $dm->createQueryBuilder('Comment')
        ->field('likes.$id')->equals(new \MongoId($user->getId()))
        ->getQuery()
        ->execute();
    

    and just to note, for references it would be:

    $dm->createQueryBuilder('Comment')
        ->field('likes')->references($user)
        ->getQuery()
        ->execute();