在 D2.1,querybuilder,我如何使用星期几 mysql 函数,我认为它不可用
doctrine but isnt there a way i could otherwise?
$qb->select('p')
->where('YEAR(p.postDate) = :year')
->andWhere('MONTH(p.postDate) = :month')
->andWhere('DAYOFWEEK(p.postDate) = :dayOfWeek');
在 D2.1,querybuilder,我如何使用星期几 mysql 函数,我认为它不可用
doctrine but isnt there a way i could otherwise?
$qb->select('p')
->where('YEAR(p.postDate) = :year')
->andWhere('MONTH(p.postDate) = :month')
->andWhere('DAYOFWEEK(p.postDate) = :dayOfWeek');
您可以编写一个学说扩展来完成这项工作:
Xyz\SomeBundle\DoctrineExtension\DayOfWeek.php
class DayOfWeek extends FunctionNode
{
public $date;
/**
* @override
*/
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return "DAYOFWEEK(" . $sqlWalker->walkArithmeticPrimary($this->date) . ")";
}
/**
* @override
*/
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->date = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
应用程序/config/config.yml
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
dql:
datetime_functions:
dayofweek: Xyz\SomeBundle\DoctrineExtension\DayOfWeek
更多细节在这里查看:DoctrineExtensions
不可能通过查询生成器使用所有 SQL 函数。其中一些已定义(AVG,SUM等),但大多数未定义(包括DAY/ WEEK/ MONTH)。
您仍然可以编写本机 SQL:
// creating doctrines result set mapping obj.
$rsm = new Doctrine\ORM\Query\ResultSetMapping();
// mapping results to the message entity
$rsm->addEntityResult('AppBundle\Entity\Post', 'p');
$rsm->addFieldResult('p', 'id', 'id');
$rsm->addFieldResult('p', 'postDate', 'postDate');
$sql = "SELECT id, postDate
FROM your_table
WHERE YEAR(postDate) = ?
AND [...]";
$query = $this->_em->createNativeQuery($sql, $rsm);
$query->setParameter(1, $your_year_here);
$query->getResult();