Colzak
Colzak

Reputation: 166

Doctrine Mongodb references()

Is it possible with doctrine mongodb createquerybuilder() to add multiple references to a document ? Here's an example of what I want to do: I have 2 collections : Users and Movements in a 1:n relation so a User has multiple movements and a movement refers to a user.

To get the movements from a user, I can do

$user->getMovements();

I can also call doctrine createQueryBuilder like this:

$query->createQueryBuilder('Movement');
$query->field('user')->references($user);

Both give me the expected results. But what if I want to fetch the movement of 2 or 3 users in one query ?

Is it possible to do something like (which I tried but did not work)

$q->field('user')->references($user1);
$q->field('user')->references($user2);
// etc.

I stuck with that kind of query. Thanks for help ! Colzak.

Upvotes: 0

Views: 151

Answers (1)

Colzak
Colzak

Reputation: 166

Ok, So I found a solution that may not be the best one but it works.

Instead of doing

$q->field('user')->references($user);

You can do

$->field('user.$id')->equals(new \MongoId($user->getId());

So if you have an array of user, you can do something like

$userIds = array();
foreach ($users as $user) {
    $userIds[] = new \MongdoId($user->getId());
}

And then the query:

$q->field('user.$id')->in($userIds);

Hope it'll help someone !

Upvotes: 2

Related Questions