Last active
December 29, 2015 01:19
-
-
Save elliotf/7592768 to your computer and use it in GitHub Desktop.
sequelize example "enforcing a foreign key reference" -- trying to get to work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"dependencies": { | |
"sequelize": "~2.0.0-beta.1", | |
"sqlite3": "~2.1.19" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Sequelize = require('sequelize') | |
, DataTypes = Sequelize | |
; | |
options = { | |
dialect: "sqlite" | |
, storage: "rssmtp_dev.sqlite" | |
}; | |
var sequelize = new Sequelize('database', 'username', 'password', options); | |
var Series, Trainer, Video | |
// Series has a trainer_id=Trainer.id foreign reference key after we call Trainer.hasMany(series) | |
Series = sequelize.define('Series', { | |
title: DataTypes.STRING, | |
sub_title: DataTypes.STRING, | |
description: DataTypes.TEXT, | |
// Set FK relationship (hasMany) with `Trainer` | |
trainer_id: { | |
type: DataTypes.INTEGER, | |
references: "Trainers", | |
referencesKey: "id" | |
} | |
}) | |
Trainer = sequelize.define('Trainer', { | |
first_name: DataTypes.STRING, | |
last_name: DataTypes.STRING | |
}); | |
// Video has a series_id=Series.id foreign reference key after we call Series.hasOne(Video)... | |
Video = sequelize.define('Video', { | |
title: DataTypes.STRING, | |
sequence: DataTypes.INTEGER, | |
description: DataTypes.TEXT, | |
// set relationship (hasOne) with `Series` | |
series_id: { | |
type: DataTypes.INTEGER, | |
references: "Serieses", | |
referencesKey: "id" | |
} | |
}); | |
Series.hasOne(Video, {foreignKeyConstraint: true}); | |
Trainer.hasMany(Series, {foreignKeyConstraint: true}); | |
sequelize.sync({force: true}).done(function(err) { | |
console.log("SYNC ERR: ", err); | |
Series.create({ title: "waffles" }).done(function(err, series){ | |
// this ought to fail due to a missing trainer_id | |
console.log("CREATE ERR: ", err); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment