问题
I am creating parent and child instance using sequlize, but it throws following error.
Site.hasMany(Group,{as:'groups'});
Group.belongsTo(Site);
//not working
Site.create(siteData).then((site)=>{
site.addGroups(groupData).then(()=>{ //also tried addGroup
next();
});
});
//this works
Site.create(siteData).then((site)=>{
groupData.SiteId=site.id;
Group.create(groupData).then(()=>{
next();
});
});
Error:
Unhandled rejection TypeError: val.replace is not a function at Object.SqlString.escape (c:\APi\node_modules\sequelize\lib\sql-string.js:61:15) at Object.QueryGenerator.escape (c:\APi\node_modules\sequelize\lib\dialects\abstract\query-generator.js:983:22)
回答1:
suppose you have a task and different schedule so you can try something like this and you can create the bulk of schedule or single task as well just change bulkeCreate to create
var ts=req.body.task_time;
tasks.create(req.body).then(function (taskvalues) {
//for adding taskId with each object to prepare object for bulk
for(var i=0;i<ts.length;i++)
ts[i].taskId = taskvalues.id;
taskschedule.bulkCreate(ts,{ individualHooks: true }).then(function (allschedule) {
res.status(200).json({"message":"Post saved successfully"});
}).catch(function (err) {
res.status(500).json(err)
}).catch(function (err) {
res.status(500).json(err);
})
})
Your json for taskschedule and whatever value set for task in post body
"task_time": [
{
"shift": "m",
"date": "01/23/2017",
"start_time": "2017-01-22 19:00:00",
"end_time": "2017-01-23 19:00:00",
"status":"2",
"user_id":"12"
},
{
"shift": "m",
"date": "01/23/2017",
"start_time": "2017-01-22 19:00:00",
"end_time": "2017-01-23 19:00:00",
"status":"2",
"user_id":"12"
}
],
回答2:
If you have any code like below adding custom properties to Object, you will face this issue.
Object.prototype.xxx = function(o) {
...
}
When Sequelize compose sql, it loops over all the properties of parameter, which will include this custom property.
来源:https://stackoverflow.com/questions/35063204/unable-to-create-child-instance-for-one-to-many-on-sequelize-js