Skip to content

Instantly share code, notes, and snippets.

@HappyZombies
Created January 6, 2017 19:03
Show Gist options
  • Save HappyZombies/61aace7077bcdf37fe1a8c0d72a1679a to your computer and use it in GitHub Desktop.
Save HappyZombies/61aace7077bcdf37fe1a8c0d72a1679a to your computer and use it in GitHub Desktop.
Sequelize Database Relations
var Sequelize = require("sequelize");
var sequelize = new Sequelize('myDatabase', 'root', '', {
host: 'localhost',
dialect: 'mysql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
var Bar = sequelize.define('bar', {
barName: Sequelize.STRING
});
var Bartender = sequelize.define('bartender', {
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
flag: {
type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true
},
barId: {
type: Sequelize.INTEGER,
reference: {
model: Bar,
key: 'id',
},
field: "bar_id"
}
});
Bartender.belongsTo(Bar, {foreignKey: 'bar_id'});
Bar.hasMany(Bartender);
Bar.sync({force: true}).then(function(){
return Bar.create({
barName: "Torres"
});
});
Bartender.sync({force: true}).then(function () {
// Table created
return Bartender.create({
firstName: 'John',
lastName: 'Hancock',
barId: 1
});
});
Bar.findOne({include:[Bartender]}).then(function(bar){
console.log("-----------------");
console.log(JSON.stringify(bar));
});
Bartender.findOne({include: [Bar]}).then(function(bartender){
console.log("-----------------");
console.log(JSON.stringify(bartender));
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment