I have a field in an entity in string type, I need order result in my dql to value integer
I have a field in an entity in string type, I need the result sorted by that field but converted in an integer.
Some like this (MySQL Query):
SELECT * FROM table1 ORDER BY CONVERT(code, UNSIGNED);
How do I create this query in doctrine?
UPDATE
I managed to do it with the cast function thanks to this post:
CASTING attributes for Ordering on a Doctrine2 DQL Query
I have created my own function to implement this feature.
Official doc in doctrine:
AFAIK You can't do it directly . Doctrine don't support native mysql functions (convert ,day,month etc). Idea od doctrine is to be able to talk with many different databases - and it's why there isn't any native functions.
but
you can do it on your own.
Some years ago i needed data functions (day/month etc ) in doctrine so i manage to add it do doctrine .
look here :
https://github.com/poznet/SF2Core/blob/master/src/Poznet/CoreBundle/Dql/Year.php or https://github.com/beberlei/DoctrineExtensions
seen solutions for conver too , but never tested it , look here
<?php
class ConvertUsing extends FunctionNode
{
public $field;
public $using;
public $charset;
/**
* @override
*/
public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
{
return sprintf('CONVERT(%s USING %s)',
$sqlWalker->walkArithmeticPrimary($this->field),
//$sqlWalker->walkSimpleArithmeticExpression($this->using), // or remove USING and uncomment this
$sqlWalker->walkSimpleArithmeticExpression($this->charset)
);
}
/**
* @override
*/
public function parse(\Doctrine\ORM\Query\Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->field = $parser->ArithmeticPrimary();
// adopt use bypass validate variable of parse by using AliasResultVariable ...!!
$this->using = $parser->AliasResultVariable();
$this->charset = $parser->AliasResultVariable();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
If you only want to sort your query you can sort the code even if it's a string like this.
SELECT * FROM table1 ORDER BY code ASC; <- for ascending
SELECT * FROM table1 ORDER BY code DESC; <- for descending
If you want to convert it to integer try this
SELECT * FROM table1 ORDER BY (SELECT CONVERT(int, code));
Just make sure your codes are all numbers so you will not get an error. I hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.