给定以下模型:

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

Project.hasMany(Task, {as: 'Tasks'});
Task.belongsTo(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
});

调用 project.save() 时,任务不会更新。为什么?

最佳答案

如果您使用 findfindAll ,则可以利用 Eager loading 中所述的预先加载。

为此,您需要使用属性 include,如:include: [Task]
这样你就有了一个内部连接,不需要查询任务。

根据您上面的代码,您可以拥有:
(我现在无法测试此代码,如果它不能完美运行,请见谅):

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

这个 answer 也可能有帮助。

关于node.js - Sequelize 在保存父对象时自动保存关联对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36612397/

10-13 02:01
查看更多