【发布时间】:2018-03-08 06:03:48
【问题描述】:
在设置与 sequelize 库的关联时遇到了一些问题。不断收到 SequelizeEagerLoadingError: Client is not associated to License!
这是我的两个模型。
'use strict';
module.exports = (sequelize, DataTypes) => {
const License = sequelize.define('License', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
validate: { isUUID: 4 }
},
client_id: {
type: DataTypes.UUID,
validate: { isUUID: 4 }
}
}, {
classMethods: {
associate: function (models) {
License.belongsTo(models.Client, { foriegnKey: 'client_id' });
}
}
});
return License;
};
'use strict';
module.exports = (sequelize, DataTypes) => {
const Client = sequelize.define('Client', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
name: { type: DataTypes.STRING }
}, {
classMethods: {
associate: function (models) {
Client.hasOne(models.License);
Client.hasMany(models.Event);
Client.hasMany(models.Clips);
}
}
});
return Client;
};
这是我设置的控制器,我知道模型工作正常,因为我使用了 findbyID() 函数进行了测试。
'use strict';
const db = require('../models/index.js');
class Controller {
constructor(router) {
router.get('/:id', (req, res, next) => {
// db.License.findById(req.params.id).then(function(license) {
// res.status(200).json(license);
// }, function(err) {
// res.status(404).json({
// error: 'License does not exist!'
// });
// });
db.License.findAll({
include: [{ model: db.Client }]
})
.then(function(license) {
res.status(200).json(license);
}, function(err) {
console.log(err);
res.status(404).json({
error: 'License does not exist!'
});
});
});
}
}
module.exports = router => new Controller(router);
帮助会很棒感觉超级迷茫。 sequelize.sync() 正在运行并且没有抛出任何错误。试图弄清楚我是否有命名问题可能是因为某些内容需要大写或不大写,而事实并非如此。
【问题讨论】:
-
刚刚意识到我的模型设置方式不适用于续集的 V4,因此没有任何关联。我使用的是 sequelize cli 迁移中的默认格式,它似乎不再起作用了。
-
你解决了吗?您正在重新定义模型上的外键。首先,您在 License 上执行 belongsTo,然后在 Client 上执行 hasOne。 belongsTo 在 origen 模型上创建键并在目标模型上创建 hasOne,除了在 belongsTo 选项上使用
as之外,当您执行 include sequelize 时,您知道您指的是哪个键。 -
是的,我想我应该关闭这个问题。由于在 sequelize V4 中为模型定义实例和类方法的新格式,我没有建立任何关联。而且由于我正在运行迁移以控制我的数据库和列名,我还必须返回并编辑它们以符合 sequqlize 的要求。 client_id => ClientId
标签: node.js sequelize.js