Sequelize bulkCreate() 为主键返回 NULL 值

2022-01-01 00:00:00 node.js orm mysql sequelize.js

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

型号

sequelize.define('category', {cat_id:{类型:DataTypes.INTEGER,字段:'cat_id',主键:真,自动增量:真,独特的:真},猫名:{类型:DataTypes.STRING,字段:'cat_name',默认值:空}});

批量创建操作:

var 数据 = [{'cat_name':'时尚'},{'cat_name':'食物'}];orm.models.category.bulkCreate(data).then(功能(响应){res.json(响应);}).catch(函数(错误){res.json(错误);})

回复:

<预><代码>[{cat_id":空,"cat_name": "时尚","created_at": "2016-01-29T07:39:50.000Z","updated_at": "2016-01-29T07:39:50.000Z"},{cat_id":空,"cat_name": "食物","created_at": "2016-01-29T07:39:50.000Z","updated_at": "2016-01-29T07:39:50.000Z"}]

解决方案

你应该设置returning选项:

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

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.

Model

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

Bulk Create operation :

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

response :

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

解决方案

You should set the returning option:

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

相关文章