Javascript sequelize为找到的对象添加值
好的,我找到了一个叫做组件的列表 一旦结果准备好,我的想法是循环浏览列表,找到所有问题的答案,然后将它们添加到单个对象中。为此,我尝试了以下方法:Javascript sequelize为找到的对象添加值,javascript,node.js,sequelize.js,Javascript,Node.js,Sequelize.js,好的,我找到了一个叫做组件的列表 一旦结果准备好,我的想法是循环浏览列表,找到所有问题的答案,然后将它们添加到单个对象中。为此,我尝试了以下方法: Component.findAll({include: [{all: true}], where: {module_id: module_id}}).then(function(components) { var i = 0; for (i = 0; i < components.length; i++) {
Component.findAll({include: [{all: true}], where: {module_id: module_id}}).then(function(components)
{
var i = 0;
for (i = 0; i < components.length; i++) {
if(components[i].dataValues.question_id != null)
{
Question_answer.findAll({where: {question_id: components[i].dataValues.question_id}}).then(function(answers)
{
var i = 0; // here i want to add the value however i cannot reach components[i]
});
}
}
})
.success(onSuccess).error(onError);
我的问题是,它是一个内部函数,我无法访问内部函数之外的变量
所以我的问题是,在使用多个查询时,如何添加附加值?Model:Component.js
模型:Question_answer.js
Fixed Controller.js
请澄清您所说的“无法触及组件[i]”是什么意思。javascript范围中的任何内容都不应阻止您这样做。但是,您正在通过声明var i来覆盖外部i,这可能会导致问题?这是因为第二个查询是异步的,并且在您想要使用组件[i]时,for循环已经结束。尝试用forEach替换for循环,这将为每个组件创建一个新函数。但在这种情况下,要注意性能问题。
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Component extends Model {
static associate(models) {
this.hasMany(models.Question_answer, {
foreignKey: "question_id",
as: 'questions'
});
}
}
Component.init({
title: { type: DataTypes.STRING, },
question_id: { type: DataTypes.INTEGER, },
}, {
sequelize,
modelName: "Component",
defaultScope: {
attributes: { exclude: ["createdAt", "updatedAt"] }
},
});
return Component;
};
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class Question_answer extends Model {
}
Question_answer.init({
testData: { type: DataTypes.STRING, },
}, {
sequelize,
modelName: "Question_answer",
defaultScope: {
attributes: { exclude: ["createdAt", "updatedAt"] }
},
});
return Question_answer;
};
Component.findAll({ include: [{ all: true }], where: { module_id: module_id } })
.then(async function (components) {
for (var i = 0; i < components.length; i++) {
if (components[i].dataValues.question_id != null) {
var answers = Question_answer.findAll({ where: { question_id: components[i].dataValues.question_id } })
// ...
// ...
}
}
})
.catch.error(onError);
Component.findAll({ include: ['questions'], where: { module_id: module_id } })
.then((components) => {
components = JSON.parse(JSON.stringify(components))
components.forEach(component => {
var questions = component.questions || [];
questions.forEach(q => {
//access question item with 'q'
console.log(q)
})
});
})
.catch.error(onError);