[TOC]
### 一對多 多對一 關聯模型
描述:
一對多: 一個部門有很多員工,但一個員工只能從屬于一個部門
多對一: 多個員工只能屬于一個部門
*****
示例:

department 部門表
employee 員工表
*****
*****
### egg-sequelize 實現一對多
分類表:

商品表:

分類 1------n 商品
1. model 里面建2張模型,分別是category.js goods.js
2. catrgory.js 模型代碼:
~~~
module.exports = app => {
const {Sequelize} = app
const {STRING,INTEGER} = Sequelize
const Category = app.model.define('category', {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
title: { type: STRING }
}, { timestamps: false , paranoid: false});
// 分類表關聯商品表 1:n
Category.associate = function() {
app.model.Category.hasMany(app.model.Goods, { as: 'goods', foreignKey: 'cate_id', targetKey: 'id'});
};
return Category;
}
~~~
3. goods.js 模型代碼:
~~~
module.exports = app => {
const {Sequelize} = app
const {STRING,INTEGER} = Sequelize
const Goods = app.model.define('goods', {
id: { type: INTEGER, primaryKey: true, autoIncrement: true },
title: { type: STRING },
price: {type: INTEGER},
cate_id: {type: INTEGER}
}, { timestamps: false , paranoid: false});
// 商品表從屬分類 n-1
Goods.associate = function() {
app.model.Goods.belongsTo(app.model.Category, { as: 'cate', foreignKey: 'cate_id', targetKey: 'id'});
};
return Goods;
}
~~~
4. controller 查詢
~~~
const {Op} = this.app.Sequelize;
const {Sequelize} = this.app;
// 查詢所有分類下對應的所有商品 分類 1----n 商品
const cate = await this.ctx.model.Category.findAll({
include: [{
model: this.ctx.model.Goods,
as: 'goods',
attributes:[[Sequelize.fn('COUNT', Sequelize.col('*')), 'total_goods']]
}],
attributes: ['title'],
group: 'title',
distinct: true
});
// 查詢商品所對應的分類 商品 n-----1 分類
const goods = await this.ctx.model.Goods.findAll({
include: [{
model: this.ctx.model.Category,
as: 'cate'
}],
distinct: true
})
~~~
- 概述
- 起步
- 跨域配置
- 路徑別名
- 路由
- api版本控制
- 錯誤和異常
- 全局異常處理
- 數據庫
- 創建遷移文件
- sequelize數據類型
- 配置
- 新增
- 查詢
- 條件查詢
- 模糊查詢
- 排序查詢
- 聚合查詢
- 分組查詢
- 分頁查詢
- 修改
- 刪除
- 獲取器
- 修改器
- 靜態屬性
- 字段驗證
- 外鍵約束
- 關聯模型
- 一對一
- 一對多
- 左外連接
- 多對多
- 字段顯示隱藏
- 事務
- 字段自增
- 驗證層
- egg-validate
- indicative驗證器
- egg-validate-plus
- betterValidate
- 校驗規則
- 中間件
- 安全
- 數據加密
- 單向加密
- 示例代碼
- 封裝egg加密
- 上傳
- path模塊
- 單文件上傳
- 多文件上傳
- 按照日期存儲
- 工具函數
- egg常用工具函數
- 緩存
- 配置緩存插件
- 設置緩存
- 獲取緩存
- 刪除緩存
- 消息隊列
- rabbitMQ
- 安裝
- 簡單隊列
- 工作隊列
- 工作隊列(dispach分發)
- 消息應答和持久化
- redis
- 數據類型
- 字符串類型(String)
- 哈希類型(Hash)
- 列表(List)
- 無序集合(Set)
- 可排序集合(Zset)
- 郵件系統
- nodeMailer
- 第三方模塊
- 生成隨機數
- JWT
- JWT鑒權
- 生成Token
- 短信服務
- 阿里大魚短信驗證碼
- 發送短信邏輯
- 阿里短信Node類