Symfony2 Doctrine - ILIKE clause for PostgreSQL?

2019-04-29 09:58发布

I'm currently using symfony2, doctrine 2.3 and PostgreSQL 9. I've been searching for a couple of hours now to see HOW on earth do I do a ILIKE select with QueryBuilder.

It seems they only have LIKE. In my situation, though, I'm searching case-insensitive. How on earth is it done?

// -- this is the "like";
$search = 'user';
$query = $this->createQueryBuilder('users');
$query->where($query->expr()->like('users.username', $query->expr()->literal('%:username%')))->setParameter(':username', $search);


// -- this is where I get "[Syntax Error] line 0, col 86: Error: Expected =, <, <=, <>, >, >=, !=, got 'ILIKE'
$search = 'user';
$query = $this->createQueryBuilder('users');
$query->where('users.username ILIKE :username')->setParameter(':username', $search);

3条回答
Evening l夕情丶
2楼-- · 2019-04-29 10:29

I don't know about Symphony, but you can substitute

a ILIKE b

with

lower(a) LIKE lower(b)

You could also try the operator ~~*, which is a synonym for ILIKE It has slightly lower operator precedence, so you might need parenthesis for concatenated strings where you wouldn't with ILIKE

a ILIKE b || c

becomes

a ~~* (b || c)

The manual about pattern matching, starting with LIKE / ILIKE.

I think this guy had the same problem and got an answer:
http://forum.symfony-project.org/viewtopic.php?f=23&t=40424

Obviously, you can extend Symfony2 with SQL vendor specific functions:
http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/cookbook/dql-user-defined-functions.html

I am not a fan of ORMs and frameworks butchering the rich functionality of Postgres just to stay "portable" (which hardly ever works).

查看更多
再贱就再见
3楼-- · 2019-04-29 10:37

From what I am aware, search queries in Symfony2 (at least when using Doctrine) are case in-sensitive. As noted in the Doctrine QL docs:

DQL is case in-sensitive, except for namespace, class and field names, which are case sensitive.

查看更多
forever°为你锁心
4楼-- · 2019-04-29 10:46

This works for me (Symfony2 + Doctrine 2)

$qq = 'SELECT x FROM MyBundle:X x WHERE LOWER(x.y) LIKE :y';
$q = $em->createQuery($qq)->setParameter(':y', strtolower('%' . $filter . '%'));
$result = $q->getResult();
查看更多
登录 后发表回答