How to aggregate information from a different table in an entity attribute in doctrine/php?

Viewed 38

I am using PHP Symfony 5.2 with doctrine-orm. I have the following entites:

Question
--------
id
questionText

Answer
------
id
answerText
questionId

GivenAnswer
-----------
id
answerId

Users go on my website and can give answers to questions. Each question has two to four answers. When the answers are sent, they are saved in the table GivenAnswer, where simply each answer creates a new row with the answerId.

Now I want to have an additional field in my Answer entity in PHP, which I would call givenTotal. There I want to access the number of given answers like this:

echo "Answer given " . $answer->givenTotal() . " times";

I know how I would request this information with SQL, but I don't want to loop over all questions with answer objects to load that information into the attribute. Is there a way to code it such, that the doctrine-orm loads the givenAnswer count into this attribute?

1 Answers

Doctrine has a feature called "extra lazy" association. On extra lazy associations count() issues a count query and doesn't completely load all associated entities.

Just add that flag to your relation from Answer to GivenAnswer:

/**
* @Entity
*/
Class Answer
{
     /**
     * @ManyToMany(targetEntity="GivenAnswer", mappedBy="answer", fetch="EXTRA_LAZY")
     */
    public $givenAnswers;

    public function getGivenAnswers() :ArrayCollection
    {
        return $this->givenAnswers;
    }
}  

and then fetch to count of any answer with $answer->getGivenAnswers()->count()

Related