gpt4 book ai didi

javascript - sequelize 为找到的对象添加值

转载 作者:行者123 更新时间:2023-12-03 22:42:41 24 4
gpt4 key购买 nike

好的,所以我找到了一个名为 component 的列表

一旦结果准备好,我的想法是遍历列表并找到所有 question_answer,然后将它们添加到单个对象中。为此,我尝试了以下操作:

    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);

我的问题是它是一个内部函数,我无法访问内部函数之外的变量。

所以我的问题是如何在使用多个查询时添加其他值?

最佳答案

型号:Component.js

"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;
};
型号: Question_answer.js
"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;
};
固定 Controller.js
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);
但是,我更喜欢下面的代码来连接两个表: Controller.js
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);

关于javascript - sequelize 为找到的对象添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29147825/

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