Skip to content

Instantly share code, notes, and snippets.

@elliotf
Created November 22, 2013 00:38
Show Gist options
  • Save elliotf/7592638 to your computer and use it in GitHub Desktop.
Save elliotf/7592638 to your computer and use it in GitHub Desktop.
struggling with sequelize foreign key constraints
var Sequelize = require('sequelize')
, _ = require('lodash')
, config = require('./config/config.json')['development']
, options
, sequelize
, Feed
, Article
;
options = {
define: {
underscored: true
, freezeTableName: true
}
, dialect: "sqlite"
, storage: "rssmtp_dev.sqlite"
};
sequelize = new Sequelize('database', 'username', 'password', options);
Feed = sequelize.define('Feed', {
url: Sequelize.STRING(2048)
}, {
tableName: "feeds"
});
Article = sequelize.define('Article', {
title: Sequelize.STRING(2048)
, feed_id: {
type: Sequelize.INTEGER
, references: "feeds"
, referencesKey: "id"
}
}, {
tableName: "articles"
});
Article.belongsTo(Feed);
Feed.hasMany(Article);
sequelize.sync({force: true}).done(function(err, models){
Article.create({
title: "Waffles"
}).done(function(err, article){
//
// this should error out because a feed_id was not specified
//
console.log("ERR: ", err);
});
});
/*
sqlite3 dump:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE `feeds` (`url` VARCHAR(2048), `id` INTEGER PRIMARY KEY AUTOINCREMENT, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
CREATE TABLE `articles` (`title` VARCHAR(2048), `feed_id` INTEGER REFERENCES `feeds` (`id`), `id` INTEGER PRIMARY KEY AUTOINCREMENT, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL);
INSERT INTO "articles" VALUES('Waffles',NULL,1,'2013-11-22 00:35:48','2013-11-22 00:35:48');
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" VALUES('articles',1);
COMMIT;
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment