gpt4 book ai didi

node.js - 如何在 Node js 中使用 sequelize 搜索多个字段?

转载 作者:行者123 更新时间:2023-12-03 22:16:48 25 4
gpt4 key购买 nike

我正在开发一个简单的博客,其中包括用户和帖子。用户和帖子有不同的字段。我想使用一个功能搜索关键字。为了实现它,我应该能够从多列中使用 sequelize 进行搜索。有关更多信息,我在下面以字典的形式提供模型的内容。

Users = {
'firstName': Sequelize.STRING,
'email': Sequelize.STRING,
'password': Sequelize.STRING,
}
Posts = {
'title': Sequelize.STRING,
'content': Sequelize.TEXT,
}
我想达到的目标:
model.findAll({
where: {
*: {
[Op.iLike]: "%searchingkeyword%"
}
})
// Imagine model is passed to function and it can either be Users or Posts
*:表示所有字段
问题:如何在不专门编写的情况下搜索多个字段?

最佳答案

我找到了答案,我真的不知道它是否可以解决。 (我来自 Python 背景!)
依赖项:
lodash - 我曾经过滤掉一些键
sequelize - 我使用了 Sequelize 的 Op

const _ = require("lodash");
const { Op } = require("sequelize");

...

const value = {
[Op.iLike]: "%" + req.query.search + "%"
}

...
const fields = Object.keys(
_.omit(model.rawAttributes, [
"password",
"id",
"createdAt",
"updatedAt",
])
);
const filters = {};
fields.forEach((item) => (filters[item] = value));

const result = await model.findAndCountAll({
where: {
[Op.or]: filters
}
});
...

关于node.js - 如何在 Node js 中使用 sequelize 搜索多个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62599130/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com