egg-sequelize 定义关联关系
定义关联关系
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 Method
Model.associate = function (models) {
...associate the models
};
// Instance Method
Model.prototype.someMethod = function () {..}
执行数据库操作,例如 findAll
的时候,如果 include
了 model
,执行之前会检测 model
之间的关联关系。如果没有提前定义,则报错 ${targetModel.name} is not associated to ${this.name}!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库