Sun*_*rma 21 mysql orm node.js sequelize.js
我正在使用node编写休息,sequelize作为mySQL的ORM.我正在使用bulkCreate函数批量创建记录.但作为响应,它为主键值返回null.
模型
sequelize.define('category', {
cat_id:{
type:DataTypes.INTEGER,
field:'cat_id',
primaryKey: true,
autoIncrement: true,
unique:true
},
cat_name:{
type: DataTypes.STRING,
field: 'cat_name',
defaultValue:null
}
});
Run Code Online (Sandbox Code Playgroud)
批量创建操作:
var data = [
{
'cat_name':'fashion'
},
{
'cat_name':'food'
}
];
orm.models.category.bulkCreate(data)
.then(function(response){
res.json(response);
})
.catch(function(error){
res.json(error);
})
Run Code Online (Sandbox Code Playgroud)
回应:
[
{
"cat_id": null,
"cat_name": "fashion",
"created_at": "2016-01-29T07:39:50.000Z",
"updated_at": "2016-01-29T07:39:50.000Z"
},
{
"cat_id": null,
"cat_name": "food",
"created_at": "2016-01-29T07:39:50.000Z",
"updated_at": "2016-01-29T07:39:50.000Z"
}
]
Run Code Online (Sandbox Code Playgroud)
Ada*_*dam 34
您应该设置returning选项:
Model.bulkCreate(values, {returning: true})
Run Code Online (Sandbox Code Playgroud)
Thi*_*ira 21
在MySQL中测试:
Model.bulkCreate(values, { individualHooks: true })
小智 6
var data = [
{
'cat_name':'fashion'
},
{
'cat_name':'food'
}
];
Model.bulkCreate(data)
.then(function() {
//(if you try to immediately return the Model after bulkCreate, the ids may all show up as 'null')
return Model.findAll()
})
.then(function(response){
res.json(response);
})
.catch(function(error){
res.json(error);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27849 次 |
| 最近记录: |