Upsert to update the association?
See original GitHub issueI have a Project model and a FacultyInfo Model and the relation between the two is:
Project.belongsTo(models.FacultyInfo, {
as : 'Faculty',
onDelete: "CASCADE"
})
Now when creating the models, I use a web form to submit the data and create both the models simultaneously as below:
var project = models.Project.create({
description: req.body.description,
url: req.body.url,
// ...
Faculty: {
name: req.body.name,
email: req.body.email,
}
}, {
include: [ {model: models.FacultyInfo, as: 'Faculty'} ]
}).then(function (task) {
//
});
And this works perfectly. Now I want to do an upsert in a similar way. In the above code, if I replace create
with upsert
, and pass in the primary key for the Project as an argument, the Project model gets updated (if found), but the FacultyInfo model does not get updated. And if the project was not found, it gets created (as expected), but the FacultyInfo model does not get created, and the faculty_id in the projects table which is the foreign key stays at Null
Maybe, there is a way to get upsert working the way I want, but I haven’t been able to find it, and I’ve searched so many posts on github/stackoverflow and what not.
I would appreciate if someone would show me how to achieve this, or show me an alternative way to achieve this.
Issue Analytics
- State:
- Created 7 years ago
- Reactions:40
- Comments:23 (4 by maintainers)
It would be the greatest feature ever! Cause for current moment I can easily CREATE instance with associations(using INCLUDE option). But if I want to update instance with some changes in instances, associated with parent one, it become really painful. Or maybe I don’t know how to do it. Any ideas, guys?
Hi everyone, I think the next step to make this feature come true is to begin suggesting what exactly it should do. I see many potential edge cases arising…
So, which SQL query exactly would you like my code above to generate?
Is there any implementation difference for HasOne / BelongsTo / HasMany / BelongsToMany here? Probably yes. How to detect if one associated entry is one that already exists but is being updated, or a new one?