Sequelize
  • Introduction
  • 写在前面的话
  • 第一章 搭建环境
  • 第二章 模型定义
    • 2.1 实例变量方法
    • 2.2 定义一个模型
    • 2.3 模型字段类型
    • 2.3 导入与配置
  • 第三章 模型关系
    • 3.1 属于
    • 3.2 包含
    • 3.3 一对多
    • 3.4 多对多
    • 3.5 多态一对多
    • 3.6 多态多对多
    • 3.7 关系嵌套
  • 第四章 模型查询
  • 第五章 查询范围 Scope (预定义查询条件)
  • 第六章 生命周期函数 Hook
  • 第七章 数据库迁移 Migrate
  • 第八章 根据 Table 生成 Model
Powered by GitBook
On this page
  • 例子
  • 新建 comment.ts
  • 新建 post.ts
  • 新建 image.ts
  • 在 index.ts 里面添加如下代码
  1. 第三章 模型关系

3.5 多态一对多

在面向对象编程里面有一个特性就是多态,多态就是适应多种情况,有的时候我们有这样一个需求。评论需求,因为网站本来就不大,所以我期望所有的评论都放在一个表里面,可以评论图片,评论文章等等。

首先评论这个是一对多的关系。所以说应该在评论表里面存储一个被评论模型(比如文章、图片)的 Id,但是这个时候呢,文章的 ID 与图片的 ID 一定会有重合的情况。例如某用户评论了 Id 为 1的文章,某用户评论了 Id 为1的图片,这个时候我们查询的时候就不清楚这个用户到底是评论了图片还说文章。

针对这一问题,我们需要在多的这一方,也就是评论表里面增加一个字段,比如 type,当 type 为 post 的时候,我们就知道是文章,当 type 为 image 的时候,我们就知道是图片。

当然这个东西可能有更专业的名称 (association scopes) ,但是我更喜欢把它理解为多态。

为了更快速的实现,就不再写接口了。关于如何定义接口让代码提示正常工作,前面的代码已经基本演示完了。

例子

新建 comment.ts

export default (sequelize, dataTypes) => {
  const Comment = sequelize.define('Comment', {
    text: dataTypes.STRING,
    type: dataTypes.STRING,
    type_id: dataTypes.INTEGER
  });

  Comment.associate = function(models) {
    this.belongsTo(models.Post);
    this.belongsTo(models.Image);
  }

  return Comment;

}

新建 post.ts

export default (sequelize, dataTypes) => {
  const Post = sequelize.define('Post', {
    title: dataTypes.STRING,
    content: dataTypes.TEXT,
  });

  Post.associate = function(models) {
    this.hasMany(models.Comment, {
      foreignKey: 'type_id',
      constraints: false,
      scope: {
        type: 'post'
      }
    });
  }

 return Post;
}

多态都是通过增加一个标识字段来区分不同的类型,而在声明关系的时候,可以通过 scope 来指定这个标识是什么,这样就可以区分开来了。constraints 是为了关闭外键所存在的约束,对于多态的,请关闭它。foreignKey 是为了指定相关联的字段值。

新建 image.ts

export default (sequelize, dataTypes) => {
  const Image = sequelize.define('Image', {
    title: dataTypes.STRING,
    imageURL: dataTypes.STRING,
  });

  Image.associate = function(models) {
    this.hasMany(models.Comment, {
      foreignKey: 'type_id',
      constraints: false,
      scope: {
        type: 'image'
      }
    });
  }

  return Image;
}

在 index.ts 里面添加如下代码

const Comment = sequelize.import('./comment');
const Post = sequelize.import('./post');
const Image = sequelize.import('./image');
   let post = await Post.create({
 title: 'name',
 content: 'some'
});

let image = await Image.create({
 title: 'image',
 imageURL: 'url'
});

console.log((post as any).__proto__)

await (post as any).createComment({
 text: 'hello'
});

await (image as any).createComment({
 text: 'hello2'
});

打印一下 (post as any).proto 我们便可知道它有哪些关于 comment 的方法。

getComments: [Function]
countComments: [Function]
hasComment: [Function]
hasComments: [Function]
setComments: [Function]
addComment: [Function]
addComments: [Function]
removeComment: [Function]
removeComments: [Function]
createComment: [Function]

记得别忘了同步数据库表,完成运行之后,可以看到所有的评论都存在了一个表里面。

Previous3.4 多对多Next3.6 多态多对多

Last updated 7 years ago