2017-01-05 4 views
0

私は最新の予約コース(ユニーク)を取得しようとしています。それが動作ORDERBYなければsymfony doctrine orderby and group by(別名)

$repository = $this->getDoctrine()->getRepository('AppBundle:Booking'); 

$query = $repository->createQueryBuilder('b') 
->select('(b.course) AS course') 
->orderBy('b.id', 'DESC') 
->groupBy('b.course') 
->setMaxResults(5) 
->getQuery(); 

が、それは予約の上昇を横断します:私はDoctrineのquerybuilderで次のことを試してみました。私は最新の予約コースが必要です。このクエリでは、私はこのエラーを取得しています:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column ... which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by 500 Internal Server Error - DriverException

私も次のことを試してみました:

$em = $this->getDoctrine()->getManager(); 
$query = $em->createQuery(
    'SELECT DISTINCT c.id 
    FROM AppBundle:Booking b 
    JOIN b.course c 
    ORDER BY b.id DESC' 
); 

SQLSTATE[HY000]: General error: 3065 Expression #1 of ORDER BY clause is not in SELECT list, references column ... which is not in SELECT list; this is incompatible with DISTINCT

今、私は解決策を探していると、基本的ONLY_FULL_GROUP_BYを無効にする提案の多くを発見しました。 Disable ONLY_FULL_GROUP_BY

一部のコメントには、SQL標準に準拠するためにそれを行うことは賢明ではないことが記載されています。それでは、これはどのように動作しますか?

+0

エンティティについての詳細情報を提供できますか?それらはどのようにマップされますか? (私はManyToOne単方向を推測しています) – OlivierC

+0

複数のカスケード削除のためにManyToOne双方向、予約がコースなしで存在することができないので – DaViDa

答えて

1

あなたはこの方法を試すことができます:

$query = $repository->createQueryBuilder('b') 
->select('(b.course) AS course') 
->leftJoin('AppBundle:Booking', 'b2', 'WITH', 'b.course = b2.course AND b.id < b2.id) 
->where('b2.id IS NULL') 
->orderBy('b.id', 'DESC') 
->setMaxResults(5) 
->getQuery(); 

あなたは偉大なすべてのコースのID、そのコースでグループ化する必要はありませんでのご予約のみを取得します。

+0

これは感謝します! – DaViDa

+0

ユニークなコースを取得する方法をどのように知っていますか? – DaViDa

+0

左に参加すると魔法が実行されます。すべてのb/b2ペアについてb.id sast