博客
关于我
egg-sequelize 定义关联关系
阅读量:728 次
发布时间:2019-03-22

本文共 1075 字,大约阅读时间需要 3 分钟。

定义关联关系

app/mode/xxx.js 中通过给模型(类)添加associate 属性,属性值为一个function(){},方法中执行sequelize提供的建立关联关系的方法,例如 belongsTo等

egg-sequelize 插件在loadDatabase的时候会associate(),建立模型之间的关系

module.exports = app => {    const { BIGINT, STRING } = app.Sequelize;    const User = app.model.define('users', {        id: {            type: BIGINT,            primaryKey: true,            autoIncrement: true,        },       team_id: BIGINT,       name: STRING,    });    User.associate = function () {        app.model.User.belongsTo(app.model.Team, { foreignKey: 'team_id' });    };    return User;};

sequelize V4版本修改了:

Removed classMethods and instanceMethods options from sequelize.define. Sequelize models are now ES6 classes. You can set class / instance level methods like this

const Model = sequelize.define('Model', {    ...});// Class MethodModel.associate = function (models) {    ...associate the models};// Instance MethodModel.prototype.someMethod = function () {..}

执行数据库操作,例如 findAll 的时候,如果 includemodel,执行之前会 model 之间的关联关系。如果没有提前定义,则 ${targetModel.name} is not associated to ${this.name}!

转载地址:http://vuywk.baihongyu.com/

你可能感兴趣的文章
Android DEX加固方案与原理
查看>>
iOS_Runtime3_动态添加方法
查看>>
Leetcode第557题---翻转字符串中的单词
查看>>
Problem G. The Stones Game【取石子博弈 & 思维】
查看>>
Java多线程
查看>>
openssl服务器证书操作
查看>>
我用wxPython搭建GUI量化系统之最小架构的运行
查看>>
selenium+python之切换窗口
查看>>
重载和重写的区别:
查看>>
搭建Vue项目步骤
查看>>
账号转账演示事务
查看>>
SpringBoot找不到@EnableRety注解
查看>>
简易计算器案例
查看>>
在Vue中使用样式——使用内联样式
查看>>
Find Familiar Service Features in Lightning Experience
查看>>
Explore Optimization
查看>>
map[]和map.at()取值之间的区别
查看>>
【SQLI-Lab】靶场搭建
查看>>
【Bootstrap5】精细学习记录
查看>>
Struts2-从值栈获取list集合数据(三种方式)
查看>>