Roby Sottini
Roby Sottini

Reputation: 2265

Yii2: accent insensitive filter

I want to search words using accent insensitive. For case insensitive I use ilike:

$query->andFilterWhere(['ilike', 'name', $this->name]);

But for accent insensitive I don't know a Yii2 solution (else I can use this PHP solution).

In the next example I search the word "camara" but it doesn't find the word "cámara" (means camera in Spanish):

No results found

Upvotes: 2

Views: 880

Answers (2)

StackUnder
StackUnder

Reputation: 252

took me a while to make this work with @rob006 comment about sql injection:

private static function ExpressionLikeAccentInsensitive($col, $field){
        $bind = md5($col);
        return [
            'ilike',
            new Expression("lower(unaccent({$col}))"),
            new Expression("'%' || lower(unaccent(:q{$bind})) || '%'", [
                ":q{$bind}"=>$field
            ]),
        ];
    }

then you call it like this (example using Postgres ILKE):

$query->andFilterWhere(self::ExpressionLikeAccentInsensitive('"DB_COLUMN"', $this->DB_COLUMN));

Upvotes: 0

Roby Sottini
Roby Sottini

Reputation: 2265

I resolved it using the lower_unaccent PostgreSQL function and the ILIKE PostgreSQL operator:

$query->andWhere(new Expression(
    'lower_unaccent(name) ILIKE \'%\' || lower_unaccent(\'' . $this->name . '\') || \'%\''
));

Upvotes: 0

Related Questions