Reputation: 4769
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 ....
Upvotes: 0
Views: 1617
Reputation: 857
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.
Upvotes: 3