LoginSignup
1
1

More than 5 years have passed since last update.

Symfony 4.2 doctrine

Posted at

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
スクリーンショット 2019-02-18 9.11.33.png

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
スクリーンショット 2019-02-18 9.13.45.png

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

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1