保存父级时,Sequelize会自动保存关联对象

时间:2016-04-14 01:41:21

标签: node.js sequelize.js

鉴于以下模型:

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()时,不会更新任务。为什么呢?

1 个答案:

答案 0 :(得分:1)

如果您使用{ "InstanceId": "i-11111111", "DeviceName": "/dev/sda1", "VolumeId": "vol-1111111a", "TAG1": "VALUE1", "TAG2": "VALUE2" } { "InstanceId": "i-11111111", "DeviceName": "xvdf", "VolumeId": "vol-1111111b", "TAG1": "VALUE1", "TAG2": "VALUE2" } { "InstanceId": "i-11111111", "DeviceName": "xvdg", "VolumeId": "vol-11111111c", "TAG1": "VALUE1", "TAG2": "VALUE2" } { "InstanceId": "i-22222222", "DeviceName": "/dev/sda1", "VolumeId": "vol-2222222a", "TAG1": "VALUE1", "TAG2": "VALUE2" } { "InstanceId": "i-22222222", "DeviceName": "/dev/sdb", "VolumeId": "vol-2222222b", "TAG1": "VALUE1", "TAG2": "VALUE2" } { "InstanceId": "i-22222222", "DeviceName": "/dev/sdc", "VolumeId": "vol-2222222c", "TAG1": "VALUE1", "TAG2": "VALUE2" } find,则可以按照Eager loading中的说明利用预先加载。

为此,您需要使用属性findAll,例如:include

这样你就有了一个内连接,不需要查询任务。

根据您的上述代码,您可以拥有:
(我现在无法测试这段代码,抱歉,如果它不能正常工作):

include: [Task]

answer也可能有所帮助。