Результаты рендеринга Query в Twig in Symfony - PullRequest
0 голосов
/ 22 апреля 2020

Я пытаюсь отобразить результат моего запроса в моем представлении. Однако я могу отобразить только часть этого результата.

Мой репозиторий с моим запросом:

public function findIdQuestion($id) {
    $query = $this->createQueryBuilder('question')
            ->andWhere('question.id_categorie = :id')
            ->leftjoin('App\Entity\Reponse','reponse','WITH','reponse.id_question = question.id')
            ->addSelect('reponse')
            ->setParameter('id', $id)
            ->getQuery();

        $results = $query->getResult();

        return $results;

  }

Вот мой контроллер:

public function play(Request $request) {

    $id = $request->query->get('id');

    $cat = $this->repository->findIdQuestion($id);

    dump($cat);

    return $this->render('quiz_select.html.twig', [
        'affichage' => $cat
    ]);
}

И моя веточка Представление:

    {% block body %}
<h1>Questions</h1>
    {% for cate in affichage %}
        <p>{{ dump(cate) }}</p>
        <p>{{ cate.question }}</p>      
    {% endfor %}
{% endblock %}

Это прекрасно работает, но мне нужно отображать также каждый ответ.

Я пробовал:

    {% for cate in affichage %}
        <p>{{ dump(cate) }}</p>
        <p>{{ cate.question }}</p>
            {% for reponse in cate.question %}
                <p>{{ reponse }}</p>
            {% endfor %}      
    {% endfor %}

Но это не так я не смог показать ничего, что я тоже пытался:

    {% for cate in affichage %}
        <p>{{ dump(cate) }}</p>
        <p>{{ cate.question }}</p>
        <p>{{ cate.reponse }}</p>     
    {% endfor %}

Но я получаю эту ошибку:

Объект класса Doctrine \ ORM \ PersistentCollection не может быть преобразован в строку

Это что я имею в моей свалке (cate):

    App\Entity\Question {#563 ▼
  -id: 21
  +id_categorie: 3
  -question: "Que signifie le verbe Enrêner ?"
  -reponse: Doctrine\ORM\PersistentCollection {#512 ▼
    -snapshot: []
    -owner: App\Entity\Question {#563}
    -association: array:15 [ …15]
    -em: Doctrine\ORM\EntityManager {#265 …11}
    -backRefFieldName: "question"
    -typeClass: Doctrine\ORM\Mapping\ClassMetadata {#518 …}
    -isDirty: false
    #collection: Doctrine\Common\Collections\ArrayCollection {#568 ▶}
    #initialized: false
  }
}
App\Entity\Reponse {#571 ▼
  -id: 31
  -id_question: 11
  -reponse: "Appellation d'Origine Contrôlée"
  -reponse_expected: 1
  -question: null
}

И это мои две сущности Вопрос:

    <?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\QuestionRepository")
 */
class Question
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    public $id_categorie;

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Reponse", mappedBy="question")
     * @ORM\JoinColumn(nullable=false)
     */
    private $reponse;

    public function setReponse(Reponse $reponse) {
        $this->reponse = $reponse;
        return $this;
    }

    public function getReponse () {
        return $this->reponse;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getIdCategorie(): ?int
    {
        return $this->id_categorie;
    }

    public function setIdCategorie(int $id_categorie): self
    {
        $this->id_categorie = $id_categorie;

        return $this;
    }

    public function getQuestion(): ?string
    {
        return $this->question;
    }

    public function setQuestion(string $question): self
    {
        $this->question = $question;

        return $this;
    }
}

Ответ:

    <?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ReponseRepository")
 */
class Reponse
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="integer")
     */
    private $id_question;

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

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $reponse_expected;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Question", inversedBy="reponse",)
     */

    private $question;

    public function setQuestion(Question $question) {
        $this->question = $question;
        return $this;
    }

    public function getQuestion () {
        return $this->question;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getIdQuestion(): ?int
    {
        return $this->id_question;
    }

    public function setIdQuestion(int $id_question): self
    {
        $this->id_question = $id_question;

        return $this;
    }

    public function getReponse(): ?string
    {
        return $this->reponse;
    }

    public function setReponse(string $reponse): self
    {
        $this->reponse = $reponse;

        return $this;
    }

    public function getReponseExpected(): ?int
    {
        return $this->reponse_expected;
    }

    public function setReponseExpected(?int $reponse_expected): self
    {
        $this->reponse_expected = $reponse_expected;

        return $this;
    }
}

1 Ответ

0 голосов
/ 22 апреля 2020

Вы действительно близки.

Во-первых, вы вручную присоединяетесь к объекту ответа, а не используете свою ассоциацию. Это портит формат результатов. Обновите свой репозиторий, чтобы присоединиться, используя OneToMany ассоциацию, определенную для сущности, например:

public function findIdQuestion($id) {
    $query = $this->createQueryBuilder('question')
            ->andWhere('question.id_categorie = :id')
            ->leftjoin('question.reponse','reponse')
            ->addSelect('reponse')
            ->setParameter('id', $id)
            ->getQuery();

        $results = $query->getResult();

        return $results;

  }

Во-вторых, вам нужно l oop cate.reponse вместо cate.question

    {% for cate in affichage %}
        <p>{{ dump(cate) }}</p>
        <p>{{ cate.question}}</p>
            {% for reponse in cate.reponse %}
                <p>{{ reponse.reponse }}</p>
            {% endfor %}      
    {% endfor %}
...