Last active
June 20, 2019 08:06
-
-
Save mickhansen/ff24863e1229946fa632 to your computer and use it in GitHub Desktop.
Sequelize Example with Users and Tasks
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 User = sequelize.define('User') | |
, Task = sequelize.define('Task'); | |
User.Tasks = User.hasMany(Task); | |
Task.User = Task.belongsTo(User); | |
/* | |
* Creation | |
*/ | |
User.create({ /* user values */ }).then(function (user) { | |
return Task.create(({ /* task values */ }).then(function (task) { | |
return user.addTask(task); | |
}); | |
// or | |
return user.createTask(({ /* task values */ }); | |
}); | |
User.create({ | |
/* user values */ | |
tasks: [ | |
{/* task values */}, | |
{/* task values */} | |
] | |
}, { | |
include: [User.Tasks] | |
}); | |
/* | |
* Fetching | |
*/ | |
User.findOne().then(function (user) { | |
return user.getTasks().then(function (tasks) { | |
}); | |
}); | |
User.findAll({ | |
include: [User.Tasks] | |
}).then(function (users) { | |
users.forEach(function (user) { | |
user.get('task'); | |
}); | |
}); |
@mschipperheyn This example is 4 years old, not sure it's completely up-to-date as i no longer maintain sequelize, IIRC createTask
should return the new task atleast. You'll probably have to look at the source code or the API documentation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is not clear from this example is what is returned from either
user.addTask
oruser.createTask