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
  1. 第三章 模型关系

3.6 多态多对多

还是就这之前标签的例子,但是为了不破坏之前的代码,这回新建一个scopeManyToMany.ts文件。代码如下。

scope 里面指定的值, 就是在连接表创建数据的时候,会自动把里面设定好的字段填充好,并且查询的时候会自动把这个条件当做 where 的一项,所以这样我们就能做出区分了。

import Sequelize from 'sequelize';

const sequelize = new Sequelize('nodelover', 'root', '', {
  host: 'localhost',
  dialect: 'mysql',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  },
});

const Post = sequelize.define('Post', {});

const ItemTag = sequelize.define('item_tag', {
  tag_id: {
    type: Sequelize.INTEGER
  },
  type: {
    type: Sequelize.STRING
  },
  type_id: {
    type: Sequelize.INTEGER
  }
});

const Tag = sequelize.define('tag', {
  name: Sequelize.STRING
});

Post.belongsToMany(Tag, {
  through: {
    model: ItemTag,
    scope: {
      type: 'post'
    }
  },
  foreignKey: 'type_id',
  constraints: false
});

Tag.belongsToMany(Post, {
  through: {
    model: ItemTag,
    scope: {
      type: 'post'
    }
  },
  foreignKey: 'tag_id',
  constraints: false
});


(async () => {
  await sequelize.sync();
  let post = await Post.create();
  await (post as any).createTag({name: '春风'});

  let tag = await Tag.create({name:'夏雨'});

  await (tag as any).createPost();
})();

挑出一段代码做个简单的说明

Tag.belongsToMany(Post, {
  through: {
    model: ItemTag,
    scope: {
      type: 'post'
    }
  },
  foreignKey: 'tag_id',
  constraints: false
});

以上代码阐述了一下内容

Tag 与 Post 建立的关系模型是 ItemTag,此时的主体是 Tag,当 Tag使用 createPost、XXXPosts、或者其他方法的时候,会自动把 ItemTag 模型里面的 type 字段填充为 Post,并且 ItemTag 与 Tag 之间有关系的字段,并且在 ItemTag 模型里面的字段叫做 Tag_id。

运行以上代码之后,便可以在数据库中看到相关的数据。

Previous3.5 多态一对多Next3.7 关系嵌套

Last updated 7 years ago