postgresql Sequelize:查询 ARRAY 是否包含值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29036363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequelize: Querying if ARRAY contains a value
提问by Calvintwr
Suppose I have a PG ARRAY field:
假设我有一个 PG ARRAY 字段:
id | array |
===|=============|
1|{"1","2","3"}|
How do I use sequelize to query to see if the array field as the value 1
.
如何使用 sequelize 查询以查看数组字段是否为值1
。
I tried:
我试过:
array: { $contains: "1" }
which gives me:
这给了我:
array @> "1"
with error:
有错误:
Possibly unhandled SequelizeDatabaseError: array value must start with "{" or dimension information
UPDATE
更新
I was able to do it by: array: { $contains: '{' + value + '}' }
我可以这样做: array: { $contains: '{' + value + '}' }
Is there a more correct way?
有没有更正确的方法?
回答by Calvintwr
I realised that sequelize is expecting the condition to be an array:
我意识到 sequelize 期望条件是一个数组:
array: { [Op.contains]: ["1"] }
That will work. Cheers!!
那可行。干杯!!
Bear in mind that Op
is exported from sequelize
请记住,Op
从sequelize
const { Op } = require('sequelize');
回答by Artash Mardoyan
Maybe so.
也许是这样。
`{ genres: { $contains: [genreType] } }`
genres
is an array. genreType
can also be an array.
genres
是一个数组。genreType
也可以是数组。
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */,
operatorsAliases: Sequelize.Op.Aliases,
});