Created
February 1, 2016 14:05
-
-
Save andrewjmead/a963c3ac6f6bc9018af1 to your computer and use it in GitHub Desktop.
Sequelize Many-to-many Example
This file contains hidden or 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'); | |
| 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.'); | |
| }); | |
| }); |
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
Sequelize magic, I spent a lot of time to understand this :(
return user.addTodos([todo])thank for this gist!