在D2.1中,查询生成器,如何使用星期一天的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(DoctrineORMQuerySqlWalker $sqlWalker)
{
return "DAYOFWEEK(" . $sqlWalker->walkArithmeticPrimary($this->date) . ")";
}
/**
* @override
*/
public function parse(DoctrineORMQueryParser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->date = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
app/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: XyzSomeBundleDoctrineExtensionDayOfWeek
更多细节在这里查看: 教义扩展
不可能
将所有 SQL 函数与查询生成器一起使用。其中一些是定义的(AVG
,SUM
等),但大多数不是(包括DAY
/WEEK
/MONTH
)。
您仍然可以编写本机 SQL:
// creating doctrines result set mapping obj.
$rsm = new DoctrineORMQueryResultSetMapping();
// mapping results to the message entity
$rsm->addEntityResult('AppBundleEntityPost', '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();
自 2016 年以来,DoctrineExtentions
存储库中有DayOfWeek
扩展。