使用 ORM
,都有一个非常核心,非常重要的功能,就是关联模型。在 Sequelize
当然一样也可以使用关联模型了。这节课呢,咱们就来一起试试看。
评论 模型
现在要来做的是,给文章添加上评论模块。然后使用关联模型,在查询文章的时候,自动查询出对应的评论。和之前添加 文章
模型一样,轻车熟路的先把 评论
模型添加了。
$ sequelize model:generate --name Comment --attributes articleId:integer,content:text
$ sequelize db:migrate
评论模型里,有一个 articleId
,大家注意下大小写,这里使用的是驼峰法,I
字母需要大写。articleId
,就是当前这篇评论对应的 文章 id
。另一个字段就是评论的内容 content
了。
然后,运行迁移命令。刷新数据库,可以看到已经有了 Comments
表了。

种子文件
接下来要做的是给 Comments
表添加一些测试数据。建一个种子文件。
$ sequelize seed:generate --name comment
插入一些默认数据
'use strict';
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('Comments', [
{
articleId: 1,
content: "这是文章1的评论",
createdAt: new Date(),
updatedAt: new Date()
},
{
articleId: 1,
content: "这个还是文章1的评论啊",
createdAt: new Date(),
updatedAt: new Date()
},
{
articleId: 2,
content: "这是文章2的评论",
createdAt: new Date(),
updatedAt: new Date()
}
], {});
},
down: (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('Comments', null, {});
}
};
执行命令后,刷新数据库
$ sequelize db:seed --seed xxxx-comment

可以看到数据已经填充进去了。咱们给 id
为 1
的文章,添加了两条评论。给 id
为 2
的文章,添加了一条评论。
关联
接下来要做的,就是建立 Article
与 Comment
之间的关联关系。
打开 models/article.js
模型。一篇文章,有很多评论,所以要定义成:
Article.associate = function (models) {
models.Article.hasMany(models.Comment)
};
再打开 models/comment.js
模型。反过来,每一篇评论,都是属于一篇文章的,所以要定义成:
Comment.associate = function(models) {
models.Comment.belongsTo(models.Article);
};
查询
关联关系定义好了后,在查询文章的时候,想把它对应的评论也给查出来,实现起来就非常简单。
将以前的 findByPk
改为 findOne
,加上 where
条件。并写上 include
,这样查询的时候,就会自动将当前文章对应的评论查出来了。
router.get('/:id', async function (req, res, next) {
var article = await models.Article.findOne({
where: {id: req.params.id},
include: [models.Comment],
})
res.json({article: article});
});
试试看
打开 Postman
,先来查看 id
为 1
的文章。
http://localhost:3000/articles/1

果然,除了文章本身,对应的两篇评论也一起查出来了。
再来试试 id
为 2
的文章。
http://localhost:3000/articles/2

同样的可以查询它对应的评论。
结束语
这节课是Node.js 入门 - 使用 Express + Sequelize 实作 API的最后一节课了。这套课程看完后,相信你对 Node.js
开发后端已经有了清晰的认识。这套课程只是抛砖引玉,如果大家想更加深入研究。一定要去仔细看看官方文档。希望通过这次课程学习后,你能使用课程中介绍的这些知识,开发出令人惊叹的项目来。
如果这套课程对你有帮助,请帮我点个赞,或帮我转发一下。感谢大家收看。
参考文档