Sequelize bulkCreate()为主键返回NULL值

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)

  • 但仅限于postgres和mssql (6认同)

Thi*_*ira 21

在MySQL中测试:

Model.bulkCreate(values, { individualHooks: true })

  • {personalHooks:true}至少在Sequelize 3中存在着误导性。不算大!抱歉成为坏消息的承担者。 (6认同)
  • 是的,但这是返回插入的ID的方法. (4认同)

小智 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)