如何用单引号和双引号转义函数?

时间:2015-04-17 14:34:50

标签: php symfony doctrine-orm

我正在尝试使用doctrine日期格式功能,以便将m-d中的日期与今天m-d进行比较,不知道如何处理addWhere中的转义,这是一个片段:

->andWhere('date("m-d", strtotime('r.dateOfDeath')) = :now')
->setParameter('now',\date("m-d", time()))

2 个答案:

答案 0 :(得分:0)

如果您的目标是通过dateOfDeath搜索特定的月/日组合,您可能会发现缺少Doctrine。

在MySQL中你通常会WHERE MONTH(r.dateOfDeath) = MONTH(NOW()) AND DAY(r.dateOfDeath) = DAY(NOW()) 为了方便您自己,您可以使用Native MySQL查询,请参阅ex。 Execute raw SQL using Doctrine 2

在Doctrine中,缺少DAY,NOW和MONTH功能。您可以使用参数解决现在的部分。你需要通过像https://github.com/beberlei/DoctrineExtensions

这样的包来实现的DAY和MONTH函数

另一种可能的解决方案可能是简单地将dateOfDeath设为字符串并执行->andWhere("r.dateOfDeath LIKE '%:md')->setParameter('md', date('m-d'))

答案 1 :(得分:0)

我使用doctrine扩展解决了这个问题[请参阅]:https://github.com/uvd/Doctrine/tree/master/UVd/DoctrineFunction“UVD Doctrine”

<强> config.yml

 orm:
    default_entity_manager: default
    entity_managers:
        default:
            connection: default
            dql:
                datetime_functions:
                    DATE_FORMAT: AppBundle\Extension\Doctrine\DateFormat

<强>用法

注册功能

 protected function registerDateFunctions() 
 {
    $emConfig = $this->getEntityManager()->getConfiguration();
    $emConfig->addCustomStringFunction('DATE_FORMAT','AppBundle\Extensions\Doctrine\DateFormat');
  }

创建查询构建器

 public function getAllRecords()
{
    $this->registerDateFunctions();
    $qb = $this->createQueryBuilder('r')
        ->select('r')
        ->addSelect('d')
        ->addSelect('b.country')
        ->leftJoin('r.religion', 're')
        ->leftJoin('r.country_of_birth', 'b')
        ->leftJoin('r.country_of_death', 'd')
        ->where('r.status = :status')
        ->setParameter(':status', 1)
        ->andWhere("DATE_FORMAT(r.dateOfDeath,'%m-%d') = :now")
        ->setParameter(':now',\date("m-d", time()))
        ->getQuery();
    return $qb->getArrayResult();

}

信用:“http://www.uvd.co.uk/blog/using-mysqls-date_format-in-doctrine-2-0/

相关问题