Skip to content

Instantly share code, notes, and snippets.

@andrewjmead
Created February 1, 2016 14:05
Show Gist options
  • Select an option

  • Save andrewjmead/a963c3ac6f6bc9018af1 to your computer and use it in GitHub Desktop.

Select an option

Save andrewjmead/a963c3ac6f6bc9018af1 to your computer and use it in GitHub Desktop.
Sequelize Many-to-many Example
var Sequelize = require('sequelize');
var sequelize = new Sequelize(undefined, undefined, undefined, {
'dialect': 'sqlite',
'storage': __dirname + '/basic-sqlite-database.sqlite'
});
var Todo = sequelize.define('todo', {
description: {
type: Sequelize.STRING,
allowNull: false,
validate: {
len: [1, 250]
}
},
completed: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
}
});
var UserTodo = sequelize.define('userTodo', {
// No attributes required, just the userId and todoId
// You could add something else here like a favorites boolean field so a user
// can mark a todo as "favorited".
});
var User = sequelize.define('user', {
email: Sequelize.STRING
});
User.belongsToMany(Todo, { through: UserTodo });
Todo.belongsToMany(User, { through: UserTodo });
sequelize.sync({
force: true
}).then(function() {
// Step One: Create a user
User.create({
email: '[email protected]'
}).then(function (user) {
// Step Two: Create Todo
return Todo.create({
description: 'Learn many-to-many associations'
}).then(function (todo) {
// Step Three: Add todo to user
return user.addTodos([todo])
});
}).then(function () {
console.log('Everything worked, check the database.');
}).catch(function () {
console.log('Something went wrong. Catch was executed.');
});
});
@WeslyG
Copy link

WeslyG commented Jun 5, 2018

Sequelize magic, I spent a lot of time to understand this :(

return user.addTodos([todo])

thank for this gist!

@ahmadudin
Copy link

Learnt about return user.addTodos([todo]) the hard way.

Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment