egg-sequelize 定义关联关系
发布日期:2021-05-25 08:44:20 浏览次数:11 分类:博客文章

本文共 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}!

上一篇:JavaScript 取模与取余
下一篇:Redis 配置 rc.local 无法开机自启动

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月15日 12时21分05秒