0
0

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 1 year has passed since last update.

DQLで日付関数とGROUP BY

Posted at

DQLでDATEカラムをGROUP BYする方法がわからなかったので調べた

#DoctrineExtensionを入れる
https://github.com/beberlei/DoctrineExtensions
でSQLの関数を追加

composer require beberlei/doctrineextensions

configs/packages/doctrine.yamlに追加

doctrine:
    orm:
        dql:
            string_functions:
                MONTH: DoctrineExtensions\Query\Mysql\Month
                YEAR: DoctrineExtensions\Query\Mysql\Year
                DATE_FORMAT: DoctrineExtensions\Query\Mysql\DateFormat

#QueryBuilder
例えばNewsPostエンティティで記事がある年を取得する

NewsPostRepository

$qb = $this->createQueryBuilder('post')
    ->select('YEAR(post.post_date) AS year')
    ->groupBy('year')
    ->orderBy('post.post_date', 'DESC')
;
// array(
//    array(
//        'year' => 2022
//    ),
//    array(
//        'year' => 2021
//    )
// )

#Group By 節に直接日付関数は使えない模様

$qb->groupBy('YEAR(post.post_date)');

とした時

[Semantical Error] line 0, col 59 near 'YEAR(post.post_date)': Error: Cannot group by undefined identification or result variable.

というエラーが出る。
select()で明示的に取得カラムにエイリアスをつけて、エイリアスでGroupByする様だ。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?