Query optimization PHP for string concatination I have an entity RegistrationForm which has a OneToMany-relationship with  SurveyAnswer. 

An answer can either have a collection of FormOptions (when the answer is of type MULTIPLE_CHOICE) or a content represented by a string (type TEXT-FIELD, TEXTAREA etc.). 

Below is a function inside the RegistrationForm-entity that tries to obtain a string-based representation of the answer's content. 

public function getAnswerByColumnId($columnId) {
    foreach ($this-&gt;surveyAnswers as $answer) {
        if ($answer-&gt;getFormQuestion()-&gt;getId() == $columnId) {
            $formOptions = $answer-&gt;getFormOptions();
            if (count($formOptions) &gt; 0) {
                $content = '';
                foreach ($formOptions as $key =&gt; $option) {
                    if ($key == 0) {
                        $content .= $option-&gt;getName();
                    } else {
                        $content .= ' , ' . $option-&gt;getName();
                    }
                }
                return $content;
            } else {
                return $answer-&gt;getContent();
            }
        }
    }
    return 'No column match, contact admin';
}


I am creating a table out of the registration forms. Each registration form has a few answers that are of a multiple-choice type. 

The result is that the foreach ($formOptions as $key =&gt; $option) {...-section is pumping the amount of queries up from 200 to 2500.  How can I improve this?
For now, one solution is to concatenate the options into a string while the answer is persisted. This is part of my FormToArrayTransformer:

switch ($_question-&gt;getFormField()-&gt;getType()) {
    case FormField::CHOICE:
        $content = '';

        foreach($answer as $_key=&gt;$option) {
            $surveyAnswer-&gt;addFormOption($option);
            if ($_key == 0) {
                $content .= $option-&gt;getName();
            } else {
                $content .= ', ' . $option-&gt;getName();
            }
        }

        $surveyAnswer-&gt;setContent($content);
        break;


Note that now both the FormOption entities and their string representation is stored. When viewing you don't have to iterate over the options anymore but simply calling answer.getContent() will do. This saved me 2300 queries in a table for 200 forms. 

I am still unsure why this is so.