Strelok
Strelok

Reputation: 51461

Sequelize automatically save association objects when parent is saved

Given the following model:

var Project = sequelize.define('project', {/* ... */})
var Task = sequelize.define('task', {/* ... */})

Project.hasMany(Task, {as: 'Tasks'});
Task.belongsTo(Project);

How can make changes to tasks and have the database updated when I save the project.

Project.findById(1, {include: Task, as: 'tasks'}).then(function(project) {
  project.tasks.each(function(task) {
    task.status = 'done';
  });
  project.status = 'closed';
  project.updatedBy = 'user';
  // ...many more statements that modify the project and tasks for example
  project.save(); // << I want this to save the whole hierarchy to the database, similar to how Hibernate does it, if some people are familiar
});

When project.save() is called, the tasks are not updated. Why?

Upvotes: 4

Views: 3043

Answers (1)

Denis C de Azevedo
Denis C de Azevedo

Reputation: 6298

If you use find or findAll you can take advantage of eager-loading as described in Eager loading.

To do this, you need to use the attribute include like: include: [Task]

This way you have an inner join and don't need to query for the tasks.

Based on your code above, you can have:
(I can't test this code right now, sorry if it's not working perfectly):

Project.find({ where: {id: 1}, include: [{model: Task, as: 'task'}]})
    .then(function(project) {      
        project.task[0].updateAttributes({
            status = 'done';
        }).then(function() {
            //done!
        });
    });

This answer may be helpful too.

Upvotes: 1

Related Questions