gpt4 book ai didi

node.js - 保存父级时,Sequelize 自动保存关联对象

转载 作者:太空宇宙 更新时间:2023-11-03 22:13:09 26 4
gpt4 key购买 nike

给定以下模型:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com