带有 Doctrine 2 查询构建器的正则表达式? [英] Regex with Doctrine 2 query builder?

查看:28
本文介绍了带有 Doctrine 2 查询构建器的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标题,如何使用 Doctrine 2 查询构建器匹配正则表达式?基本上我正在尝试生成独特的 slug.

As per the title, how would one match on a regular expression with the Doctrine 2 query builder? Basically I'm trying to generate unique slugs.

这是我目前的实现.我生成弹头.然后我检查是否有任何像这个 slug 一样的 slug 正在使用中.如果有,我将在 slug 的末尾附加一个 -{number},其中 {number} 是尚未使用的最小数字.

Here is my current implementation. I generate the slug. I then check to see if there are any slugs in use like this slug. If there are, I will append a -{number} to the end of the slug where {number} is the lowest number not already in use.

$qb->select(array('partial o.{id, slug}'))
   ->from('FooBarEntityObject', 'o')
   ->where($qb->expr()->like('o.slug', ':slug'));

$slug = new SlugNormalizer($text);
$qb->setParameter('slug', $slug->__toString().'-%');

这里的问题是 LIKE slug% 可以匹配 foo-bar-1、foo-bar-2 和 foo-bar-not-the-same-slug.更简洁的是正则表达式寻找 REGEX slug-(d+) 或类似的东西.

The problem here is LIKE slug% could match foo-bar-1, foo-bar-2, AND foo-bar-not-the-same-slug. What would be cleaner is a regex looking for REGEX slug-(d+) or something similar.

有没有办法用 Doctrine 2 查询构建器来做到这一点?

Any way to do this with the Doctrine 2 query builder?

推荐答案

安装DoctrineExtensionsBundle::>

composer require beberlei/doctrineextensions

添加 REGEXP 配置 - 更新您的 app/config.yml

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

doctrine:
    orm:
        dql:
            string_functions:
                regexp: DoctrineExtensionsQueryMysqlRegexp

您的 QueryBuilder 在哪里执行此操作:

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();

并且不要忘记使用 SQL 兼容的正则表达式

and don't forget to use SQL compatible regexes

这篇关于带有 Doctrine 2 查询构建器的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆