2

独自のメソッドを作成したいのですがfindBy()。私には2つのエンティティがあります:FilmGenre。このカスタムfindBy()メソッドの目的は次のとおりです。

  • Filmエンティティとエンティティを結合して、Genreすべての私の映画と関連するジャンルを取得します。
  • 基本メソッドのパラメーターである、、、およびを$criteria保持 し$orderByます。$limit$offset

実際、私はこれらのパラメーターを使用してページングを作成します。

以前、2つのエンティティ間の結合を使用してカスタムfindAllメソッドを作成しました。

<?php
public function myFindAll()
{
    $films = $this->createQueryBuilder('f')
        // leftJoin because I need all the genre
        ->leftJoin('f.genres', 'g')
        ->addSelect('g.label')
        ->groupBy('f.id')
        ->getQuery()
        ->getArrayResult();

    // $genres contains all the genres and the associated movies
    return ($films);
}

残りのパラメータを含める方法がわかりません。

4

1 に答える 1

1

スライス()はどうですか?

$genders = $em->getRepository('models\Gender')->findAll()->slice($offset, $lenght);

また、次のような関数を利用できます。

public function myFindAll($criteria, $orderBy, $limit, $offset)
{
    $films = $this->createQueryBuilder('f')
        // leftJoin because I need all the genre
        ->leftJoin('f.genres', 'g')
        ->addSelect('g.label')
        ->groupBy('f.id')
        ->add('orderBy', "f.{$orderBy} ASC")
        ->getQuery()
        ->getArrayResult()
        ->slice($offset, $limit);

    // $films contains all the genres and the associated movies
    return ($films);
}

編集:

このslice()関数はページネーション関数として機能します。

$page1 = $films->slice(0, 15); // retrieve films from 0 to 15 position
$page2 = $films->slice(10, 7); // retrieve films from 10 to 17 position

ここで、いくつかの基準値を使用する場合は、次のようにすることができます。

public function myFindAll($criteria, $orderBy, $limit, $offset)
{
    $films = $this->createQueryBuilder('f');

    foreach($criteria as $column => $value)
        $films->where($column, $value);

    $films
        ->leftJoin('f.genres', 'g')
        ->addSelect('g.label')
        ->groupBy('f.id')
        ->add('orderBy', "{$orderBy[0]} {$orderBy[1]}");
        ->getQuery()
        ->getArrayResult()
        ->slice($offset, $limit);

    // $genres contains all the genres and the associated movies
    return ($films);
}

関数が以前の条件をオーバーライドするかどうかwhereはわかりませんが、少なくとも正しいクエリを見つけることができます

setFirstResult()およびsetMaxResult()

また、使用できる別のオプションがあります。

public function myFindAll($criteria, $orderBy, $limit, $offset)
{
    $films = $this->createQueryBuilder('f');

    foreach($criteria as $column => $value)
        $films->where($column, $value);

    $films
        ->leftJoin('f.genres', 'g')
        ->addSelect('g.label')
        ->groupBy('f.id')
        ->add('orderBy', "f.{$orderBy[0]} {$orderBy[1]}")
    ->setFirstResult($offset)
    ->setMaxResults($limit)
        ->getQuery()
        ->getArrayResult();

    // $genres contains all the genres and the associated movies
    return ($films);
}
于 2012-08-02T18:58:36.207 に答える