Is there a way to update an object (organization) and it’s associations (tasg) in a single call? In my case I have Orgs -> tags. One org can have many tags.
I can’t figure out how to update the tags as well as the organization in one simple call
function updateOrganization(db, stats) {
return function (req, res) {
let myOrg
db.organization.findOne({
where: {
id: req.params.id
},
include: ['tags']
})
.then(org => {
myOrg = org
let promises = []
if (req.body.tags) {
req.body.tags.forEach(tag => {
promises.push(org.createTag({ name: tag }))
})
}
return Promise.all(promises)
})
.then(tags => {
console.log('tags = ', tags)
return myOrg.setTags(tags) <-- DOES NOT SEEM TO BE WORKING
})
.then(updatedOrg => {
console.log('updatedOrg.get() = ', updatedOrg.get()) <-- DOES NOT CONTAIN NEW TAGS
console.log('myOrg final = ', myOrg.get()) <-- DOES NOT CONTAIN NEW TAGS
return res.status(HttpStatus.OK).send(myOrg)
})
.catch(err => {
req.log.error(err)
return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
})
}
}
NOTE: It looks like the line promises.push(org.createTag({ name: tag })) is actually creating the tags and the line return myOrg.setTags(tags) is not necessary. When i fetch this record with a findOne query, all the tags do actually exist. So why don't they appear when in my log statements which is the output of updatedOrg?
from How to update hasMany associations when updating model?
No comments:
Post a Comment