2

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.

j0k
  • 22,600
  • 28
  • 79
  • 90
Senči
  • 911
  • 2
  • 10
  • 25

1 Answers1

3

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();
MDrollette
  • 6,887
  • 1
  • 36
  • 49