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.
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('Foo\Bar\Entity\Object', 'o')
->where($qb->expr()->like('o.slug', ':slug'));
$slug = new SlugNormalizer($text);
$qb->setParameter('slug', $slug->__toString().'-%');
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.
Any way to do this with the Doctrine 2 query builder?
Not tested (for MySQL):
I did like this
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:
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!
add the DoctrineExtensionsBundle - update your composer.json:
add the REGEXP configuration - update your app/config.yml
where ever your QueryBuilder is do this:
and don't forget to use SQL compatible regexes