0

I am doing my project with express and sequelizejs.And it's my first time to try sequellize,I have some associations between two tables,goods and goodsImg.I was working on the associations and I was hard to solved the problem.please help.

Goods Model :

"use strict";
module.exports = function(sequelize, DataTypes) {
  var Goods = sequelize.define('Goods', {
    id: {
        type: DataTypes.BIGINT,
        primaryKey:true,
        allowNull: false
    },
    goodsID:{
        type:DataTypes.STRING,
        allowNull: false
    } ,
     ...
},{
      classMethods: {
          associate: function(models) {
              Goods.hasMany(models.GoodsImg, { onDelete: 'SET NULL', onUpdate: 'CASCADE' });
          }
      }
  });

  return Goods;
};

goodsImg Model:

module.exports = function(sequelize, DataTypes) {
  var GoodsImg = sequelize.define('GoodsImg', {
    id: {
        type: DataTypes.BIGINT,
        primaryKey:true,
        allowNull: false
    },
    goodsID:{
        type:DataTypes.STRING,
        allowNull: false,
        references : 'goods',
        referencesKey:'id'
    } ,
    ....  
},{
      classMethods:{
          associate: function(models){
              GoodsImg.belongsTo(models.Goods,{ foreignKey: 'id', foreignKeyConstraint:true });
          }
      }
  });

  return GoodsImg;
};

when use sync() It can generated a goods table in databases and the goodImg can't. And came out an error:

Executing (default): SHOW INDEX FROM Goods Possibly unhandled
SequelizeDatabaseError: Error: ER_CANNOT_ADD_FOREIGN: Cannot add
foreign key constraint ....

Ryan Yiada
  • 4,739
  • 4
  • 18
  • 20
  • http://stackoverflow.com/questions/22958683/how-to-implement-many-to-many-association-in-sequelize I think this will help you. – Anuj Nov 26 '14 at 08:47

1 Answers1

3

Might I suggest you run:

SHOW ENGINE INNODB STATUS\G

And check the section (here's an example):

------------------------
LATEST FOREIGN KEY ERROR
------------------------
... 
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
martyman
  • 867
  • 8
  • 14