简体   繁体   English

使用Sequelize on for循环findAll查询并合并结果

[英]Use Sequelize on for loop findAll query and merge result

I'm coding opensource project in the university course 我正在大学课程中编码开源项目

It is a function to search the value of another table by dividing input keyword by comma. 通过将输入关键字除以逗号来搜索另一个表的值的功能。

under this example data 在此示例数据下

Python,CPP,Csharp Python中,CPP,Csharp的

var keyword = result[0].keyword;
var keyword_arr = [];
var keyword_split = keyword.split(',');
for (var i in keyword_split)
{
   keyword_arr.push(keyword_split[i]);
}

I have succeeded in separating them with commas like above, but I'm looking for a loop in sequelize. 我已经成功地用上面的逗号分隔了它们,但是我正在寻找续集中的一个循环。

"Error: Can not set headers after they are sent." “错误:发送后无法设置标题。”

An error is returned and is not executed. 返回错误并且不执行。

I want to output the results merged. 我想输出合并的结果。 What should I do? 我该怎么办?

my code is 我的代码是

for (i = 0; i < keyword_arr.length; i++) {
    query += models.contents.findAll({
        where: {keyword: {like: '%' + keyword_arr[i] + '%'}},
        raw: true
    });
}

Regards. 问候。

You were in the right direction , but here it his how you can do : 您的方向是正确的,但是在这里他的工作方法是:

queries = [];

for (i = 0; i < keyword_arr.length; i++) {
    queries.push({keyword: {like: '%' + keyword_arr[i] + '%'}});
}

models.contents.findAll({
    where: {
        $or : queries
    }
    raw: true
}).then(results => {
    console.log(results); // <---- Check this
})

NOTES : 注意事项:

models.contents.findAll() //<---- Returns promises

You can't just combine the promises by += as its not string or number like that 您不能只用+ =来组合诺言,因为它不是这样的字符串或数字

In your case , it will create and run the query for each tag , so that's not proper way of doing , you should combine the tags and create a single query as I did 在您的情况下,它将为每个标签创建并运行查询,因此这不是正确的方法,您应该像我一样组合标签并创建一个查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM