3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SymfonyでN+1問題を解決する

Last updated at Posted at 2018-08-15

会員情報のEntity Customer と都道府県のEntity Pref がManyToOneの関係にあるとする。

例えば以下のようなコードを書くとlazyloadでクエリが N+1 回実行されてしまう。

$qb = $this->entityManager->createQueryBuilder();

$Customers = $qb
    ->from(Customer::class, 'c')
    ->select('c')
    ->getQuery()
    ->getResult();

foreach ($Customers as $Customer) {
    dump($Customer->getPref()->getName());
}

この場合は明示的にJoinしてやるとクエリの数が減らせる。
addSelect() で指定してやることであらかじめJoinしたデータを取得してくれる。

$qb = $this->entityManager->createQueryBuilder();

$Customers = $qb
    ->from(Customer::class, 'c')
    ->select('c')
    ->addSelect('p')// この行を追加
    ->leftJoin('c.Pref', 'p')// この行を追加
    ->getQuery()
    ->getResult();

foreach ($Customers as $Customer) {
    dump($Customer->getPref()->getName());
}
3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?