- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试使用 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.js
, question.js
)并执行 sequelize.import()
为了将这些模型分配给 sequelize 实例 - 这允许您稍后通过 sequelize[modelName]
访问它们例如sequelize.question
.
注意:创建迁移文件时请记住时间戳字段 - createdAt
, updatedAt
最终,deletedAt
.
我个人使用sync()
仅当我运行测试时 - 这可能分三个步骤显示
sequelize.sync({ force: true })
为了同步所有模型seeds
(也可以通过 sequelize-cli
完成),这很舒服,因为允许您在运行测试之前清理数据库,并且为了区分开发和测试,测试可以使用不同的数据库,例如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! 错误。这是因为您关联了 Mentee
与 Question
但 MenteeQuestion
之间没有关联和 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/
我正在努力实现以下目标, 假设我有字符串: ( z ) ( A ( z ) ( A ( z ) ( A ( z ) ( A ( z ) ( A ) ) ) ) ) 我想编写一个正则
给定: 1 2 3 4 5 6
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
大家好,我卡颂。 Svelte问世很久了,一直想写一篇好懂的原理分析文章,拖了这么久终于写了。 本文会围绕一张流程图和两个Demo讲解,正确的食用方式是用电脑打开本文,跟着流程图、Demo一
身份证为15位或者18位,15位的全为数字,18位的前17位为数字,最后一位为数字或者大写字母”X“。 与之匹配的正则表达式: ?
我们先来最简单的,网页的登录窗口; 不过开始之前,大家先下载jquery的插件 本人习惯用了vs2008来做网页了,先添加一个空白页 这是最简单的的做法。。。先在body里面插入 <
1、MySQL自带的压力测试工具 Mysqlslap mysqlslap是mysql自带的基准测试工具,该工具查询数据,语法简单,灵活容易使用.该工具可以模拟多个客户端同时并发的向服务器发出
前言 今天大姚给大家分享一款.NET开源(MIT License)、免费、简单、实用的数据库文档(字典)生成工具,该工具支持CHM、Word、Excel、PDF、Html、XML、Markdown等
Go语言语法类似于C语言,因此熟悉C语言及其派生语言( C++、 C#、Objective-C 等)的人都会迅速熟悉这门语言。 C语言的有些语法会让代码可读性降低甚至发生歧义。Go语言在C语言的
我正在使用快速将 mkv 转换为 mp4 ffmpeg 命令 ffmpeg -i test.mkv -vcodec copy -acodec copy new.mp4 但不适用于任何 mkv 文件,当
我想计算我的工作簿中的工作表数量,然后从总数中减去特定的工作表。我错过了什么?这给了我一个对象错误: wsCount = ThisWorkbook.Sheets.Count - ThisWorkboo
我有一个 perl 文件,用于查看文件夹中是否存在 ini。如果是,它会从中读取,如果不是,它会根据我为它制作的模板创建一个。 我在 ini 部分使用 Config::Simple。 我的问题是,如果
尝试让一个 ViewController 通过标准 Cocoa 通知与另一个 ViewController 进行通信。 编写了一个简单的测试用例。在我最初的 VC 中,我将以下内容添加到 viewDi
我正在绘制高程剖面图,显示沿路径的高程增益/损失,类似于下面的: Sample Elevation Profile with hand-placed labels http://img38.image
嗨,所以我需要做的是最终让 regStart 和 regPage 根据点击事件交替可见性,我不太担心编写 JavaScript 函数,但我根本无法让我的 regPage 首先隐藏。这是我的代码。请简单
我有一个非常简单的程序来测量一个函数花费了多少时间。 #include #include #include struct Foo { void addSample(uint64_t s)
我需要为 JavaScript 制作简单的 C# BitConverter。我做了一个简单的BitConverter class BitConverter{ constructor(){} GetBy
已关闭。这个问题是 not reproducible or was caused by typos 。目前不接受答案。 这个问题是由拼写错误或无法再重现的问题引起的。虽然类似的问题可能是 on-top
我是 Simple.Data 的新手。但我很难找到如何进行“分组依据”。 我想要的是非常基本的。 表格看起来像: +________+ | cards | +________+ | id |
我现在正在开发一个 JS UDF,它看起来遵循编码。 通常情况下,由于循环计数为 2,Alert Msg 会出现两次。我想要的是即使循环计数为 3,Alert Msg 也只会出现一次。任何想法都
我是一名优秀的程序员,十分优秀!