使用 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, {}); } };执行命令后,刷新数据库 xxxx-comment代表目录seeders/2020102017816548-comment.js名
$ sequelize db:seed --seed xxxx-comment可以看到数据已经填充进去了。咱们给 id 为 1 的文章,添加了两条评论。给 id 为 2 的文章,添加了一条评论。
接下来要做的,就是建立 Article 与 Comment 之间的关联关系。
关联关系定义好了后,在查询文章的时候,想把它对应的评论也给查出来,实现起来就非常简单。
将以前的 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
同样的可以查询它对应的评论。