Skip to content

Instantly share code, notes, and snippets.

@mickhansen
Last active June 20, 2019 08:06
Show Gist options
  • Save mickhansen/ff24863e1229946fa632 to your computer and use it in GitHub Desktop.
Save mickhansen/ff24863e1229946fa632 to your computer and use it in GitHub Desktop.
Sequelize Example with Users and Tasks
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
Copy link

What is not clear from this example is what is returned from either user.addTask or user.createTask

@mickhansen
Copy link
Author

@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