node用express写后端restful接口实战九:表的关联,评论模型

使用 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 

迁移

可以看到数据已经填充进去了。咱们给 id1 的文章,添加了两条评论。给 id2 的文章,添加了一条评论。

三、关联

接下来要做的,就是建立 ArticleComment 之间的关联关系。

打开 models/article.js 模型。一篇文章,有很多评论,所以要定义成:

Article.associate = function (models) {
    models.Article.hasMany(models.Comment)
};

完整的models/article.js

'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Article extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };

  Article.init({
    title: DataTypes.STRING,
    content: DataTypes.TEXT
  }, {
    sequelize,
    modelName: 'Article',
  });
  //定义与comment数据表,即评论关联
  Article.associate = function (models) {
    models.Article.hasMany(models.Comment)
  };
  return Article;
};

再打开 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,先来查看 id1 的文章。

http://localhost:3000/articles/1

关联查询

果然,除了文章本身,对应的两篇评论也一起查出来了。

再来试试 id2 的文章。

http://localhost:3000/articles/2

关联查询

同样的可以查询它对应的评论。

posted @ 2020-10-20 15:47  晨光曦微  阅读(252)  评论(0编辑  收藏  举报