Sequelize混合错误

时间:2015-10-23 02:37:06

标签: mysql node.js sequelize.js

我正在尝试将我的Images表与我的Description表关联,方法是为我的单个模型创建两个js文件,然后在索引文件中关联模型。两个表之间的关系是图像只能有一个描述,但描述可以有多个图像,如我的文件所示。尽管如下,我收到了以下错误:

 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;

1 个答案:

答案 0 :(得分:4)

当您使用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;

通过调用关联方法,您将调用Images模型的关联类方法。并且您将要更改图像模型中的关联类方法,这样您就不会收到错误:

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