Sequelize bulkCreate() 返回主键的 NULL 值 [英] Sequelize bulkCreate() returns NULL value for primary key

查看:23
本文介绍了Sequelize bulkCreate() 返回主键的 NULL 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 node 编写 rest,sequelize 作为 mySQL 的 ORM.我正在使用 bulkCreate 函数批量创建记录.但作为响应,它为主键值返回 null.

I am writing rest using node, sequelize as ORM for mySQL. I am using bulkCreate function to create record in bulk. But in response it is returning null for primary key value.

型号

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
    }
});

批量创建操作:

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);
    })

回复:

[
  {
    "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"
  }
]

推荐答案

你应该设置 returning 选项:

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

这篇关于Sequelize bulkCreate() 返回主键的 NULL 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆