30. Pagination

Doctrine ORM ships with a Paginator for DQL queries. It has a very simple API and implements the SPL interfaces Countable and IteratorAggregate.

Doctrine ORM には、DQL クエリ用のページネーターが同梱されています。これは非常に単純な API を持ち、SPL インターフェースの Countable と IteratorAggregate を実装しています。

<?php
use Doctrine\ORM\Tools\Pagination\Paginator;

$dql = "SELECT p, c FROM BlogPost p JOIN p.comments c";
$query = $entityManager->createQuery($dql)
                       ->setFirstResult(0)
                       ->setMaxResults(100);

$paginator = new Paginator($query, $fetchJoinCollection = true);

$c = count($paginator);
foreach ($paginator as $post) {
    echo $post->getHeadline() . "\n";
}

Paginating Doctrine queries is not as simple as you might think in the beginning. If you have complex fetch-join scenarios with one-to-many or many-to-many associations using the “default” LIMIT functionality of database vendors is not sufficient to get the correct results.

Doctrine クエリのページネーションは、最初に考えたほど単純ではありません。 1 対多または多対多の関連付けを伴う複雑なフェッチと結合のシナリオがある場合、データベース ベンダーの「デフォルト」の LIMIT 機能を使用しても正しい結果を得るには不十分です。

By default the pagination extension does the following steps to compute the correct result:

デフォルトでは、ページネーション拡張機能は次の手順を実行して正しい結果を計算します。

  • Perform a Count query using DISTINCT keyword.

    DISTINCT キーワードを使用してカウント クエリを実行します。

  • Perform a Limit Subquery with DISTINCT to find all ids of the entity in from on the current page.

    DISTINCT で制限サブクエリを実行して、現在のページからエンティティのすべての ID を検索します。

  • Perform a WHERE IN query to get all results for the current page.

    WHERE IN クエリを実行して、現在のページのすべての結果を取得します。

This behavior is only necessary if you actually fetch join a to-many collection. You can disable this behavior by setting the $fetchJoinCollection flag to false; in that case only 2 instead of the 3 queries described are executed. We hope to automate the detection for this in the future.

この動作は、to-manycollection を実際にフェッチして結合する場合にのみ必要です。 $fetchJoinCollection フラグを false に設定すると、この動作を無効にできます。その場合、前述の 3 つのクエリではなく 2 つのクエリのみが実行されます。今後、この検出を自動化する予定です。

Note

ノート

$fetchJoinCollection flag set to true might affect results if you use aggregations in your query.

$fetchJoinCollection フラグを true に設定すると、クエリで集計を使用する場合に結果に影響する可能性があります。

Previous topic

Override Field Association Mappings In Subclasses

サブクラスでのフィールド関連付けマッピングのオーバーライド

Next topic

Separating Concerns using Embeddables

Embeddables を使用して懸念事項を分離する

This Page

Fork me on GitHub