gpt4 book ai didi

javascript - 使用 Sequelize 的多对多关系的简单示例

转载 作者:IT老高 更新时间:2023-10-28 23:10:30 27 4
gpt4 key购买 nike

我正在尝试使用 Sequelize 构建表之间多对多关系的简单示例。但是,这似乎比我预期的要棘手。

这是我目前拥有的代码(./db.js 文件导出 Sequelize 连接实例)。

const Sequelize = require("sequelize");
const sequelize = require("./db");

var Mentee = sequelize.define('mentee', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING
}
});

var Question = sequelize.define('question', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
text: {
type: Sequelize.STRING
}
});

var MenteeQuestion = sequelize.define('menteequestion', {
// answer: {
// type: Sequelize.STRING
// }
});

// A mentee can answer several questions
Mentee.belongsToMany(Question, { as: "Questions", through: MenteeQuestion });

// And a question can be answered by several mentees
Question.belongsToMany(Mentee, { as: "Mentees", through: MenteeQuestion });

let currentQuestion = null;
Promise.all([
Mentee.sync({ force: true })
, Question.sync({ force: true })
, MenteeQuestion.sync({ force: true })
]).then(() => {
return Mentee.destroy({where: {}})
}).then(() => {
return Question.destroy({ where: {} })
}).then(() => {
return Question.create({
text: "What is 42?"
});
}).then(question => {
currentQuestion = question;
return Mentee.create({
name: "Johnny"
})
}).then(mentee => {
console.log("Adding question");
return mentee.addQuestion(currentQuestion);
}).then(() => {
return MenteeQuestion.findAll({
where: {}
, include: [Mentee]
})
}).then(menteeQuestions => {
return MenteeQuestion.findAll({
where: {
menteeId: 1
}
, include: [Mentee]
})
}).then(menteeQuestion => {
console.log(menteeQuestion.toJSON());
}).catch(e => {
console.error(e);
});

运行时我得到:

Cannot add foreign key constraint

我认为这是因为 id 类型——但我不知道它出现的原因以及我们如何修复它。

前一个错误不会出现时出现的另一个错误是:

Executing (default): INSERT INTO menteequestions (menteeId,questionId,createdAt,updatedAt) VALUES (2,1,'2017-03-17 06:18:01','2017-03-17 06:18:01');

Error: mentee is not associated to menteequestion!

另外,我得到的另一个错误——我认为这是因为 sync 中的 force:true——是:

DROP TABLE IF EXISTS mentees;

ER_ROW_IS_REFERENCED: Cannot delete or update a parent row: a foreign key constraint fails

如何解决这些问题?

再次,我只需要一个多对多 crud 操作的最小示例(在这种情况下只是插入和读取),但这似乎超出了我的理解。为此苦苦挣扎了两天。

最佳答案

迁移

我建议你使用 sequelize migrations而是做 sync()在每个模型上。有一个模块 - sequelize.cli这使您可以轻松管理迁移和种子。它以某种方式通过创建初始化文件 index.js 来强制一个项目结构。里面 /models项目目录。它假定您的所有模型定义都将在此目录中。该脚本遍历所有模型文件(每个模型定义在单独的文件中,例如 mentee.jsquestion.js )并执行 sequelize.import()为了将这些模型分配给 sequelize 实例 - 这允许您稍后通过 sequelize[modelName] 访问它们例如sequelize.question .

注意:创建迁移文件时请记住时间戳字段 - createdAt , updatedAt最终,deletedAt .

同步

我个人使用sync()仅当我运行测试时 - 这可能分三个步骤显示

  1. 执行 sequelize.sync({ force: true })为了同步所有模型
  2. 运行一些数据库seeds (也可以通过 sequelize-cli 完成),
  3. 运行测试。

这很舒服,因为允许您在运行测试之前清理数据库,并且为了区分开发和测试,测试可以使用不同的数据库,例如project_test ,以便开发数据库保持完整。

多对多

现在让我们继续讨论您的问题 - 两个模型之间的 m:n 关系。首先,由于您执行 Promise.all() , sync可以以与在其中添加功能不同的顺序运行。为了避免这种情况,我建议您使用 mapSeries Bluebird 的特点 promise ,Sequelize 在 sequelize.Promise 下使用和公开(这也是您关于删除父行的最后一个错误的原因 - 您尝试删除从 mentees 引用的 menteequestion )。

sequelize.Promise.mapSeries([
Mentee.sync({ force: true })
, Question.sync({ force: true })
, MenteeQuestion.sync({ force: true })
], (model) => { return model.destroy({ where: {} }); }).then(() => {

});

mapSeries 的第一个参数是一组 promise ,但是第二个是一个函数,它使用每个先前定义的 promise 的结果运行。由于 Model.sync()结果是模型本身,我们可以执行model.destroy()每次迭代。

之后,您可以通过create() 向数据库中插入一些数据。 ,就像在示例中一样。现在是时候修复 错误:mentee is not associated to menteequestion! 错误。这是因为您关联了 MenteeQuestionMenteeQuestion 之间没有关联和 Mentee (或 Question)。为了解决这个问题,在 belongsToMany 之后,你可以添加

MenteeQuestion.belongsTo(Mentee, { foreignKey: 'menteeId' });
MenteeQuestion.belongsTo(Question, { foreignKey: 'questionId' });

现在您可以添加 include: [Mentee, Question]查询时MenteeQuestion .在执行 toJSON() 时,您还会遇到另一个错误。 , 因为你做 findAll它返回实例数组。你可以做forEach()

menteeQuestions.forEach(menteeQuestion => {
console.log(menteeQuestion.toJSON());
});

关于javascript - 使用 Sequelize 的多对多关系的简单示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42850631/

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