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 的時候,如果 includemodel,執行之前會檢測 model 之間的關聯關系。如果沒有提前定義,則報錯 ${targetModel.name} is not associated to ${this.name}!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM