Symfony retrieve data from Array Collection

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.

Controller Code:

$question = $this->getDoctrine()
            ->getRepository('QuizBundle:Question')
            ->findByIdJoinedToCategory();
return $this->render('QuizBundle:Default:admin.html.twig', array('data' => $question));

Question Repository:

public function findByIdJoinedToCategory()
    {
        $query = $this->getEntityManager()
            ->createQuery(
                'SELECT a, q FROM QuizBundle:Question a
                JOIN a.answers q');
        try {
            return $query->getResult();
        } catch (\Doctrine\ORM\NoResultException $e) {
            return null;
        }
    }

Twig Code:

{% for item in data %}
              <tbody>
                <tr>
                    <th scope="row">{{ item.id }}</th>
                    <td>{{ item.image }}</td>
                    <td>{{ item.question }}</td>
                    <td></td>
                <tr>
               <tbody>

{% endfor %}

Dump screenshot of the data from the query:

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.

`/**
 * Question
 *
 * @ORM\Table(name="question")
 * @ORM\Entity(repositoryClass="QuizBundle\Repository\QuestionRepository")
 */
class Question
{
    /**
     * @ORM\OneToMany(targetEntity="Answer", mappedBy="question")
     */
    private $answers;
    public function __construct()
    {
        $this->answers = new ArrayCollection();
    }

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image;

    /**
     * @var string
     *
     * @ORM\Column(name="question", type="string", length=255)
     */
    private $question;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set image
     *
     * @param string $image
     *
     * @return Question
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set question
     *
     * @param string $question
     *
     * @return Question
     */
    public function setQuestion($question)
    {
        $this->question = $question;

        return $this;
    }

    /**
     * Get question
     *
     * @return string
     */
    public function getQuestion()
    {
        return $this->question;
    }

    /**
     * Add answer
     *
     * @param \QuizBundle\Entity\Answer $answer
     *
     * @return Question
     */
    public function addAnswer(\QuizBundle\Entity\Answer $answer)
    {
        $this->answers[] = $answer;
        return $this;
    }

    /**
     * Remove answer
     *
     * @param \QuizBundle\Entity\Answer $answer
     */
    public function removeAnswer(\QuizBundle\Entity\Answer $answer)
    {
        $this->answers->removeElement($answer);
    }
    /**
     * Get answers
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getAnswers()
    {
        return $this->answers;
    }
}`

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.

I have found out a solution for someone that might be interested:

In your controller:

$questions = $this->getDoctrine()
            ->getRepository('QuizBundle:Question')->findAll();
return $this->render('QuizBundle:Default:admin.html.twig', array('data' => $questions));

In your Twig :

{% for question in data %}
    <tbody>
        <tr>
            <th scope="row">{{ question.id }}</th>
            <td>{{ question.image }}</td>
            {% for answer in question.answers %}
                {{ answer.id }}
            {% endfor %}
        <tr>
    <tbody>
{% endfor %}

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();
  }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.