Symfony 4.2 doctrine


OneToMany の取得方法

Entity

Person Class

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="person")
     */
    private $messages;

Message Class

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Person", inversedBy="messages")
     */
    private $person;

Template

    <h2>Person Table</h2>
    <table>
        <tr>
            <th>id</th>
            <th>name</th>
            <th>mail</th>
            <th>age</th>
            <th>messages</th>
        </tr>
        {% for person in data %}
            <tr>
                <td>{{ person.id }}</td>
                <td>{{ person.name }}</td>
                <td>{{ person.mail }}</td>
                <td>{{ person.age }}</td>
                <td>
                    <ul>
                        {% for msg in person.messages %}
                            <li>{{ msg.content }}</li>
                        {% endfor %}
                    </ul>
                </td>
            </tr>
        {% endfor %}
    </table>

Case1. 都度データを取得する例

        $repository = $this->getDoctrine()
                           ->getRepository(\App\Entity\Person::class);
        $data = $repository->findAll();

Symfony Profiler

Case2. まとめてデータを取得する例

        $repository = $this->getDoctrine()
                           ->getRepository(\App\Entity\Person::class);
        $data = $repository
            ->createQueryBuilder('p')
            ->select('p')
            ->addSelect('m')
            ->leftJoin('p.messages', 'm', Expr\Join::ON)
            ->getQuery()
            ->getResult();

Symfony Profiler

Case3. フェッチモードを変える

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="person", fetch="EAGER")
     */
    private $messages;