node.js - Sequelize : How to match atleast 1 value from array stored in db with array in the request

标签 node.js json postgresql sequelize.js

我在 psql 数据库中有一个表,如下所示。

[{
 name="ABC",
 email="xyz",
 animals=["cats","dogs","elephants","giraffes"]
},
{
 name="BCD",
 email="fgh",
 animals=["giraffes"]
}]
....

以及我将在请求中获取的数组,如下所示

hasAnimals=["lion","cheetah","dog","cat"]

如何使用sequelize where子句来获取上表中所有拥有hasAnimals数组中至少1只动物的人的记录。

例如。上述示例应该为我获取名为 ABC 的用户,因为 ABC 有猫和狗,我在请求中获得的数组也是如此

最佳答案

事实证明,解决方案非常简单。

const { Op } = require("sequelize");
let arr = []
for(let animal of animals) {
    arr.push({
        [Op.contains]: [animal],
    });
}

abc.findAll({
   where: {
      animals: {
         [Op.or]: arr
      }
   },    
})

关于node.js - Sequelize : How to match atleast 1 value from array stored in db with array in the request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69893770/

相关文章:

python - Django - order_by 是如何工作的?

ruby-on-rails - ActiveRecord PSQL 按最近创建的 has_many 关联 + 分页排序

node.js - 除非作为参数传入,否则无法添加快速路线

ios - 服务器应如何代表 iOS 用户进行身份验证?

python - 创建流程树形式的 json 文件。在Python中

javascript - 类型错误 : Cannot set property of undefined returned JSON issue using Realtime Firebase in Vue. js

sql - 如何将 VARIANT 数据插入雪花表?

ruby - 如何获取 ruby​​ 脚本中 fatal error 的确切消息

javascript - FFmpeg HLS 单个文件扩展名和按字节范围格式化

c++ - 遍历文件,只得到一行