Sequelize:如何将存储在数据库中的数组中的至少 1 个值与请求中的数组匹配
Sequelize: How to match atleast 1 value from array stored in db with array in the request
我在 psql 数据库中有一个 table,如下所示。
[{
name="ABC",
email="xyz",
animals=["cats","dogs","elephants","giraffes"]
},
{
name="BCD",
email="fgh",
animals=["giraffes"]
}]
....
以及我将在请求中获得的数组,如下所示
hasAnimals=["lion","cheetah","dog","cat"]
如何使用 sequelize where 子句获取上述 table 中至少拥有 hasAnimals 数组中的一种动物的所有人的记录。
例如。所述示例应该为我获取名称为 ABC 的用户,因为 ABC 有猫和狗,我在请求中得到的数组也是如此
sql
解决方案可能是这样的:
SELECT *
FROM your_table
WHERE your_json_column :: jsonb @? '$[*].animals[*] ? (@ <@ HasAnimals)'
事实证明解决方案非常简单。
const { Op } = require("sequelize");
let arr = []
for(let animal of animals) {
arr.push({
[Op.contains]: [animal],
});
}
abc.findAll({
where: {
animals: {
[Op.or]: arr
}
},
})
我在 psql 数据库中有一个 table,如下所示。
[{
name="ABC",
email="xyz",
animals=["cats","dogs","elephants","giraffes"]
},
{
name="BCD",
email="fgh",
animals=["giraffes"]
}]
....
以及我将在请求中获得的数组,如下所示
hasAnimals=["lion","cheetah","dog","cat"]
如何使用 sequelize where 子句获取上述 table 中至少拥有 hasAnimals 数组中的一种动物的所有人的记录。
例如。所述示例应该为我获取名称为 ABC 的用户,因为 ABC 有猫和狗,我在请求中得到的数组也是如此
sql
解决方案可能是这样的:
SELECT *
FROM your_table
WHERE your_json_column :: jsonb @? '$[*].animals[*] ? (@ <@ HasAnimals)'
事实证明解决方案非常简单。
const { Op } = require("sequelize");
let arr = []
for(let animal of animals) {
arr.push({
[Op.contains]: [animal],
});
}
abc.findAll({
where: {
animals: {
[Op.or]: arr
}
},
})