I use Sequelize for my Server (with mysql dialect); in Sequelize's documentation is written that this:
var Task = this.sequelize.define('Task', { title: Sequelize.STRING })
, User = this.sequelize.define('User', { username: Sequelize.STRING })
User.hasMany(Task)
Task.belongsTo(User)
creates automatically foreign key references with constraints; but for me this doesn't happen:
var Shop = sequelize.define('Shop', {
name: Sequelize.STRING,
address: Sequelize.STRING,
phone: Sequelize.STRING,
email: Sequelize.STRING,
percentage: Sequelize.FLOAT,
text: Sequelize.TEXT,
categories: Sequelize.TEXT,
start: Sequelize.DATE,
end: Sequelize.DATE
});
var Offer = sequelize.define('Offer', {
name: Sequelize.STRING,
deadline: Sequelize.DATE,
optionDuration: Sequelize.INTEGER
});
Shop.hasMany(Offer);
Offer.belongsTo(Shop);
This creates the two tables shops and offers, both of them with only "id" primary key
I also have some n:m associations like:
Group.hasMany(Accesslevel);
Accesslevel.hasMany(Group);
but also in this case, in the join table that Sequelize creates, there are no foreign key; so if I delete for ex. an acccesslevel, than the corresponding records in the join table accesslevelsgroups are not deleted.
Does anybody know if I'm doing something wrong or missing something? What I need is to create all the foreign keys for the associations and the possibility to specify the behaviour 'onDelete' and 'onUpdate' (cascade)
-- UPDATE I've created a route for executing sync:
myServer.get('/sync', function (req, res) {
sequelize.sync({force: true}).success(function() {
console.log('sync done');
res.send(200, 'sync done');
}).error(function(error) {
console.log('there was a problem');
res.send(200, 'there was a problem');
});
});
So then in the browser I type 127.0.0.1:port/sync to create the db structure
Did you add the relation after creating the table ( in the database ) ?
You need .sync({ force: true })
if you modify your scheme's and run your program again.
Sequelize will only create the table and all it's references if the table does not exist yet in the database.
Are you calling sync after all associations have been made ?
Are you using InnoDB ?
Oddly enough I can reproduce that, The easiest fix is to define the key manually I think, that's how I solved it, Might be a bug otherwise I'm not sure.
See here: http://sequelizejs.com/docs/latest/associations#block-3-line-24
You should give foreign keys like that, it is not related to sync.
Offer.associate = function (models) {
models. Offer.belongsTo(models. Offer, {
onDelete: "CASCADE",
foreignKey: 'shopId',
targetKey: 'id'
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With