DQL User-Defined Functions

From Littledamien Wiki
Revision as of 03:31, 18 February 2015 by Video8 (talk | contribs) (Created page with "Category:Symfony Category:Doctrine Category:CMS Category:Web Development == Objective == Doctrine doesn't support MySQL's `YEAR()` function, as it doesn't tra...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Objective

Doctrine doesn't support MySQL's YEAR() function, as it doesn't translate to the other databases that Doctrine supports.

A dropdown control filters listings by year. The records store the date value as datetime which includes year, month, date, etc.

In MySQL SELECT t.* FROM MyTable t WHERE YEAR(t.create_date) = :year. It's necessary to define this function for Doctrine in order to use it.

What it does

A custom function returns the SQL that can be used by Doctrine to interpret YEAR() in DQL.

This will only work for MySQL, which goes against the intent of using Doctrine.

User-defined function

The user-defined function translates the DQL to native MySQL.[1]

namespace NorthRose\InvoiceBundle\DQL;

use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;

class Year extends FunctionNode
{
	public $yearExpression;
	
	public function parse(\Doctrine\ORM\Query\Parser $parser )
	{
		$parser->match(Lexer::T_IDENTIFIER);
		$parser->match(Lexer::T_OPEN_PARENTHESIS);
		$this->yearExpression = $parser->ArithmeticPrimary();
		$parser->match(Lexer::T_CLOSE_PARENTHESIS);
	}
	
	public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
	{
		return 'YEAR('.$this->yearExpression->dispatch($sqlWalker).')';
	}
}

Notes

  1. Registering Your Own DQL Functions, Doctrine 2 ORM 2 Documenttaion