我和Sequelize合作了几个星期,我遇到了这个问题。我已经读过其他类似的问题,但似乎没有任何帮助。
让我告诉你我的模特:
Merchants.js 'use strict';
var Sequelize = require('sequelize');
var config = require(__base + '/server/config/config').provisioning;
var sequelize = new Sequelize(config.database, config.user, config.password, config);
var Merchants = sequelize.define('merchants', {
id: {
type: Sequelize.UUID,
primaryKey: true,
unique: true,
defaultValue: Sequelize.UUIDV4
},
name: {
type: Sequelize.STRING(255)
},
createdAt: {
type: Sequelize.DATE,
field: 'created_at'
},
//more attributes
}, {
classMethods: {
associate: function (models) {
Merchants.hasOne(models.Users, {foreignKey: 'merchantId'})
}
}
});
module.exports = Merchants;
Users.js
'use strict';
var Sequelize = require('sequelize');
var config = require(__base + '/server/config/config').provisioning;
var sequelize = new Sequelize(config.database, config.user, config.password, config);
var Users = sequelize.define('users', {
id: {
type: Sequelize.UUID,
primaryKey: true,
unique: true,
defaultValue: Sequelize.UUIDV4
},
merchantId: {
type: Sequelize.UUID,
field: 'merchant_id'
},
createdAt: {
type: Sequelize.DATE,
field: 'created_at'
},
// more attributes
}, {
classMethods: {
associate: function (models) {
Users.belongsTo(models.Merchants, { foreignKey: 'merchantId' });
}
}
});
module.exports = Users;
然后我试着这样做:
Users.findAll({
include: [{
model: Merchants,
where: { state: 'ACTIVATED' }
}]
}).then(function (users) {
console.log(users.length);
}).catch(function (err) {
console.log(err);
});
我得到了:[Error: merchants is not associated to users!]
我已经完成了一些我在不同问题中阅读的内容,但似乎没有任何效果。这可能是一个愚蠢的事情,但正如我之前所说,第一次与Sequelize合作。
答案 0 :(得分:0)
确保实际正在设置关联 - 请注意associate
方法不是sequelize API的一部分,但仅仅是一种常见模式 - 你必须确保它实际上被称为。例如:
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach(function(file) {
var model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if ("associate" in db[modelName]) {
db[modelName].associate(db);
}
});