gpt4 book ai didi

node.js - 错误 : XModel is not associated to Ymodel on Sequelizejs

转载 作者:行者123 更新时间:2023-12-03 22:41:57 25 4
gpt4 key购买 nike

我有几周的时间与 Sequelize 合作,但我遇到了这个问题。我已经阅读了其他类似的问题,但似乎没有任何帮助。

让我向您展示我的模型:

商户.js
'使用严格';

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;

用户.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 合作。

最佳答案

确保实际建立了关联 - 请注意 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);
}
});

https://github.com/sequelize/express-example/blob/master/models/index.js

关于node.js - 错误 : XModel is not associated to Ymodel on Sequelizejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38256717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com