2016-11-19 57 views
0

我在我的應用程序兩個「模式」被分流到不同的文件:屬於關聯使用聯想似乎並沒有工作

ApplicationSession.model.js

module.exports = function(sequelize, DataTypes) { 

    const { INTEGER, DATE } = DataTypes; 

    var ApplicationSession = sequelize.define("applicationSession", { 
     sessionStart: DATE, 
     sessionEnd: DATE 
    }, { 
     associate: (models) => { 
      ApplicationSession.belongsTo(models.User, { 
       foreignKey: 'userId', 
       as: 'User', 
      }); 
     } 
    }); 

    return ApplicationSession; 
}; 

User.model.js

module.exports = function(sequelize, DataTypes) { 

    const { STRING, INTEGER, DATE } = DataTypes; 

    var User = sequelize.define("user", { 
     name: STRING 
    }, { 
     associate: (models) => { 
      User.hasMany(models.ApplicationSession); 
     } 
    }); 

    return User; 
}; 

當保存表(DROPING/RECREATING)force: true和手動丟棄僅用於理智時,永遠不會爲用戶創建一個字段。

這裏是我如何我的加載不同型號

import fs from 'fs'; 
import path from 'path'; 
import sequelize from '../connection'; 
var exports = {}; 

fs.readdirSync(__dirname).forEach(fileName => { 
    if(~fileName.indexOf('.model.js')) { 
     const subname = fileName.replace('.model.js', ''); 

     const model = sequelize.import(path.join(__dirname, fileName)); 
     exports[subname] = model; 
    } 

}); 

export default exports; 

當所有的車型在一個單一的文件中聲明,我可以使用X.belongsTo(Y)沒有任何問題,所以我想我會嘗試加入這我sequelize.import下稱

exports['ApplicationSession'].belongsTo(exports['User'], { as: 'User', foreignKey: 'userId' }); 
    exports['User'].hasMany(exports['ApplicationSession']); 

然而,這產生了不同的錯誤:

/node_modules/sequelize/lib/associations/mixin.js:96 
     throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model'); 
    ^

Error: applicationSession.function BelongsTo(source, target, options) 

我該怎麼做才能使人際關係發揮作用?

回答

0

您需要在模型加載模塊中添加一件以使關聯工作。

fs.readdirSync(__dirname).forEach(fileName => { 
    if(~fileName.indexOf('.model.js')) { 
     const subname = fileName.replace('.model.js', ''); 
     const model = sequelize.import(path.join(__dirname, fileName)); 
     exports[subname] = model; 
    } 
}); 

// You need to check for every model if it has `associate` class method 
// and execute it 
Object.keys(exports).forEach(function(modelName) { 
    if ("associate" in exports[modelName]) { 
    exports[modelName].associate(db); 
    } 
}); 

我還在代碼中看到了另一個錯誤。在您的模型associate中定義的類方法應該包含classMethods屬性。

它應該是這樣的:

var ApplicationSession = sequelize.define("applicationSession", { 
    sessionStart: DATE, 
    sessionEnd: DATE 
}, { 
    // Add this 
    classMethods: { 
     associate: (models) => { 
      ApplicationSession.belongsTo(models.User, { 
       foreignKey: 'userId', 
       as: 'User', 
      }); 
     } 
    } 
}); 

您可以通過sequelize在GitHub下面的例子。

+0

這是我的問題中的一個錯誤,他們是這樣命名的,對不起。編輯:修復了問題 – Hobbyist

+0

更新了我的anawer – drinchev

相關問題