Regex with Doctrine 2 query builder?

拟墨画扇 提交于 2019-11-28 12:00:48

add the DoctrineExtensionsBundle - update your composer.json:

"beberlei/DoctrineExtensions": "0.3.x-dev",

add the REGEXP configuration - update your app/config.yml

doctrine:
    orm:
        dql:
            string_functions:
                regexp: DoctrineExtensions\Query\Mysql\Regexp

where ever your QueryBuilder is do this:

$qb = $this->createQueryBuilder('x');

return $qb->andWhere('REGEXP(x.your_property, :regexp) = true')
          ->setParameter('regexp', '[[:digit:]]{3}') // insert your own regex here
          ->getQuery()->getResult();

and don't forget to use SQL compatible regexes

Chadwick Meyer

REGEXP is a vendor specific function so Doctrine itself doesn't support it. Plus it's not a function so much as a comparison operator (see this answer). But you can use the function on the field to compare with another value. DoctrineExtensions (written by a contributor to doctrine) has code to enable regular expression in MySQL.

Example from the File:

$query = $this->getEntityManager()->createQuery('SELECT A FROM Entity A WHERE REGEXP(A.stringField, :regexp) = 1');
$query->setParameter('regexp', '^[ABC]');
$results = $query->getArrayResult();

If you don't want to use DoctrineExtensions, you can write your own by following this blog post, or you can look at the code for this Doctrine extension and write your own custom DQL function.

I have confirmed that REGEXP using DoctrineExtensions works great for my needs!

I did like this

 $query->andWhere('REGEXP(r.status, :text) = 1')
       ->orWhere('REGEXP(r.comment, :text) = 1')
       ->setParameter('text',MY REGULAR EXP);

Not tested (for MySQL):

$qb->where(new Doctrine\ORM\Query\Expr\Comparison(
    'o.slug', 'REGEXP', ':slug')
);
$qb->setParameter('slug', '^'.$slug->__toString().'-[[:digit:]]+$');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!