Reputation: 1380
I have two documents, Question and Answer. The Question class has an $answers
property defined as @MongoDB\ReferenceMany(targetDocument="Answer", cascade="all")
. The Answer class has a $question
property defined as @MongoDB\ReferenceOne(targetDocument="Question")
. Both classes have an $id
property defined as @MongoDB\Id
.
I need to return a partial array of all the answers for a single question, say in groups of 10.
I've tried a number of different approaches, all with varying results. None of the approaches have yielded what I need.
Querying the Question repo
$question = $this->getDocumentManager()
->getRepository(self::QUESTION_REPO)
->find($id);
$answers = array($questions->getAnswers());
That'll get me the answers but not 10 at a time.
Querying the Answer repo (version 1)
$question = $this->getQuestion($id); // works just fine
$answers = $this->getDocumentManager()
->createQueryBuilder(self::ANSWER_REPO)
->field('question.$id')->equals(new \MongoId($question->getId()))
->getQuery()
->execute();
This query will return an empty object.
Querying the Answer repo (version 2)
$question = $this->getQuestion($id);
$answers = $this->getDocumentManager()
->createQueryBuilder(self::ANSWER_REPO)
->field('question')->references($question)
->getQuery()
->execute();
This query will return an empty object too.
Querying the Answer repo (version 3)
$question = $this->getQuestion($id);
$answers = $this->getDocumentManager()
->getRepository(self::ANSWER_REPO)
->findBy(array('question.id' => $question->getId()));
This query will return an empty object too.
Querying the Answer repo (version 4)
$question = $this->getQuestion($id);
$answer = $this->getDocumentManager()
->getRepository(self::ANSWER_REPO)
->findOneBy(array('question.id' => $question->getId()));
// note: 'question.id' and not 'question.$id'
This query will return the expected object - a single Answer - to my great surprise.
So, the question I have is, what am I missing?
I'd prefer not to "embed" my documents, although I've read that it's easier to query on embedded documents that way. Maybe I can embed the Question in the Answer.
Upvotes: 0
Views: 595
Reputation: 36
The result of Query::execute()
and DocumentRepository::findBy()
will return a Cursor so it will not contain any actual data inside the object. Are you sure that it is empty? If you start iterating over the $answers or do $answers->count()
it should work.
Upvotes: 2