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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:49:23  来源:igfitidea点击:

Sequelize: Querying if ARRAY contains a value

postgresqlsequelize.js

提问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 Opis exported from sequelize

请记住,Opsequelize

const { Op } = require('sequelize');

回答by Artash Mardoyan

Maybe so.

也许是这样。

`{ genres: { $contains: [genreType] } }`

genresis an array. genreTypecan 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,
});