0

我需要查询一个不带重音符号(á、í、ö 等)的 postgresdb。

我已经使用 Knex.js 作为查询构建器,并且 postgresql 有一个 unaccent 扩展,可以在直接对 db 的 sql 查询中正常工作,但是在我的代码中我使用 knex 和 unaccent 函数在查询中引发错误。

谁能帮助我,¿是否可以使用 knex.js 使用 postgresql 的非重音功能进行查询?

4

1 回答 1

0

我的解决方案是在使用以下代码提交查询之前处理字符串:

const normalize = (str) => str.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
console.log(normalize('Ấ Á Ắ Ạ Ê')) -> 'A A A A A'.

或者,如果您使用 postgresql 版本 13 或更高版本,它已经支持该功能。

select normalize('hồ, phố, ầ', NFC) → 'ho, pho, a' -- NFC (the default), NFD, NFKC, or NFKD.

文档:https ://www.postgresql.org/docs/13/functions-string.html

于 2021-07-24T07:45:22.263 回答