SQL查询转换为DQL(Sytrfony2的Doctrine)

时间:2016-01-18 11:00:54

标签: php symfony doctrine-orm dql

如何在DQL(Symfony2)中使用此查询:

SELECT id FROM user WHERE DATE_FORMAT( birth_date ,'%m-%d') = DATE_FORMAT( NOW() + INTERVAL 7 DAY ,'%m-%d')

我使用beberlei / DoctrineExtensions,我添加了这是我的配置:

orm:
dql:
    string_functions:
        date_format: DoctrineExtensions\Query\Mysql\DateFormat
        dateadd: DoctrineExtensions\Query\Mysql\DateAdd

我在UserRepository中尝试了这个:

$qb = $this->createQueryBuilder('U');
$qb ->select('U')
    ->where( 'DATE_FORMAT( U.birthDate, %m-%d) = DATE_FORMAT( CURRENT_TIMESTAMP() + INTERVAL 7 DAY, %m-%d' );

但它不起作用。

提前致谢!

1 个答案:

答案 0 :(得分:1)

要加载生日为7天的所有用户:

// Using DQL
$dql = "SELECT u FROM user u WHERE DATE_FORMAT(u.birthDate, '%m-%d') = DATE_FORMAT(:dateIn7Days, '%m-%d')";

$query = $em->createQuery($dql);
$query->setParameter('dateIn7Days', new \DateTime('+7 days'));

$users = $query->getResult();

使用QueryBuilder:

$qb = $this->createQueryBuilder();

$qb
   ->select('u')
   ->from('User', 'u')
   ->where(
       $qb->expr()->eq(
           "DATE_FORMAT(u.birthDate, '%m-%d')",
           "DATE_FORMAT(:dateIn7Days, '%m-%d')")
       )
   ->setParameter('dateIn7Days', new \DateTime('+7 days'));

$query = $qb->getQuery();
$users = $query->getResult();