Sequelize 混入错误

Sequelize Mix-In Errors

我正在尝试将我的 Images table 关联到我的 Description table,方法是按照为我的个人模型创建两个 js 文件然后关联索引文件中的模型。两个table的关系是Images只能有一个Description,但是一个Description可以有多个Images,如我的文件所示。尽管遵循示例,我还是收到以下错误:

 throw new Error(this.name + '.hasMany called with something that\'s not an
          ^
Error: description.hasMany called with something that's not an instance of Sequelize.Model
    at Mixin.hasMany (/Users/user/Desktop/Projects/node/assistant/node_modules/sequelize/lib/associations/mixin.js:168:11)
    at Object.<anonymous> (/Users/user/Desktop/Projects/node/assistant/app/models/dbIndex.js:14:13)

这是我的图片模型:

module.exports = function(sequelize, DataTypes){

var Images = sequelize.define('images', {
    pattern: DataTypes.STRING,
    color: DataTypes.STRING,
    imageUrl: DataTypes.STRING,
    imageSource: DataTypes.STRING,
    description_id: DataTypes.INTEGER
}, {
    classMethods: {
        associate: function(db) {
            Images.belongsTo(models.description, {foreignKey: 'description_id'});
        }
    }
});
    return Images;
}

描述型号:

module.exports = function(sequelize, DataTypes) {

var Description = sequelize.define('description', {
    description_id: {
        type: DataTypes.INTEGER,
        primaryKey: true
    },
    color: DataTypes.STRING,
    body: DataTypes.STRING
});
    return Description;
}

dbIndex 模型,连接两个模型:

var Sequelize      = require('sequelize');
var sequelize = new Sequelize("db", "admin", "pwd", {
    host: "localhost",
    port: 3306,
    dialect: 'mysql'
});
var db = {};


var Description = sequelize.import(__dirname + "/descriptionModel");

var Images = sequelize.import(__dirname + "/imagesModel");

Description.hasMany('Images');
Images.belongsTo('Description');

module.exports = db;

当您使用 hasManybelongsTo 为模型定义关联时,当您发送字符串而不是作为续集模型的变量时,您没有遵循正确的语法。这导致了您收到的错误。

我假设您正在尝试按照示例 here 进行操作。如果您想逐个导入模型而不是通过编程方式搜索目录,您可以将索引文件修改为:

var Sequelize      = require('sequelize');
var sequelize = new Sequelize("db", "admin", "pwd", {
    host: "localhost",
    port: 3306,
    dialect: 'mysql'
});

var db = {};
db.Description = sequelize.import(__dirname + "/descriptionModel");
db.Images = sequelize.import(__dirname + "/imagesModel");

db.Images.associate(db);

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

通过调用associate 方法,您将调用Images 模型的associate classmethod。你会想要改变图像模型中的关联类方法,这样你就不会得到错误:

associate: function(db) {
  Images.belongsTo(db.Description, {foreignKey: 'description_id'});
}