Hi. In Symfony I am using a query to retrieve all questions and their relative answers from a database. Using a for in twig I am trying to display in a table all questions with the relative answers row by row. At the moment I am able to access and display the questions only but not the answers. The relation between my entities Questions and Answers is (one to many) thus when retrieving the question, also the answers are retrieved. Using dump, I can see the the answers are put in an Array Collection.
Trying to get only a single question from the database with another query, using the getAnswers() function from my Question entity I am able to get the answers from the array collection using this statement:
$answer = $question->getAnswers()->getValues();
Using this statement I tried to get the answers for all the questions using the bellow code in the controller, but I get this error:
Error: Call to a member function getAnswers() on a non-object
I believe this is because the query returns multiple questions and not just one. How can I get the answers for each individual question from the Array Collection? Thanks in advance for the help.
Post the code for the question entity. The error says no getAnswers method exists on that entity. No magical methods exist to access the answers on the question. There must be an explicitly defined method on that entity which does that. My guess is that method has not been defined.
In your repository you’re fetching a collection rather than the first entity. There is an explicit method to call on a query that will fetch a single entity. I don’t know it off hand.
That solution doesn’t eager load the answers. A separate query will be executed for every question to load the questions answers. The method you’re looking for instead of getResult is getOneOrNullResult.
public function findByIdJoinedToCategory()
{
$query = $this->getEntityManager()
->createQuery(
'SELECT a, q FROM QuizBundle:Question a
JOIN a.answers q');
return $query->getOneOrNullResult();
}