I want to use the sql function MD5 in my Symfony bundle so I added the file (https://gist.github.com/Basster/2774738) in \MyCompany\MyBundle\DQL\MD5Function.
Then I changed my config.yml file :
# app/config/config.yml
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Added configuration for MD5 function
entity_managers:
default:
dql:
string_functions:
MD5: MyCompany\MyBundle\DQL\MD5Function
But I have the following error :
InvalidConfigurationException in ArrayNode.php line 309: Unrecognized options "naming_strategy, auto_mapping" under "doctrine.orm"
You mix the one entity manager configuration and the multi entity manager one.
You should use:
# app/config/config.yml
doctrine:
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Added configuration for MD5 function
dql:
string_functions:
MD5: MyCompany\MyBundle\DQL\MD5Function
or:
# app/config/config.yml
doctrine:
orm:
entity_managers:
default:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Added configuration for MD5 function
dql:
string_functions:
MD5: MyCompany\MyBundle\DQL\MD5Function
Alternatively you can create your own class to do that like explained here How to create and use custom built doctrine DQL function in symfony. Funny enough the example is based on SHA1 so you can just simply change the SH1 to MD5, like I did below.
Your custom MD5 class
namespace Football\FrontendBundle\DQL;
use Doctrine\ORM\Query\AST\Functions\FunctionNode;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
class Md5 extends FunctionNode
{
public $value;
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->value = $parser->StringPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
public function getSql(SqlWalker $sqlWalker)
{
return 'MD5(' . $this->value->dispatch($sqlWalker) . ')';
}
}
Register it in config.yml
doctrine:
orm:
dql:
string_functions:
MD5: Football\FrontendBundle\DQL\Md5
And use it in your repository like this
namespace Football\FrontendBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
class CountryRepository extends EntityRepository
{
public function findOneCountryBy($id)
{
return
$this
->createQueryBuilder('c')
->select('c, MD5(c.code) AS code')
->where('c.id = :id')
->setParameter('id', $id)
->getQuery()
->getSingleResult(Query::HYDRATE_SCALAR);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With