【问题标题】:return last inserted id sequelize返回最后插入的 id 续集
【发布时间】:2015-11-24 03:06:34
【问题描述】:

在 sequlize 中创建新条目时如何发送最后插入的 id?

目前这是创造新价值的典范方式:

function post( request, response ) {

    models.xxx.create( {

            field1: request.body.field1,
            field2: request.body.field2

        } )
        .then( function ( x ) {

            //x = 0 || 1;
            response.json( x );
            //What I would like to send is the `id` of the new row

        } );

}

sequelize 有可能吗,还是我必须查询表?

【问题讨论】:

  • x 应该是您新创建的行,因此它的 id 为 no ? x.getId()
  • 我不知道为什么,但是当我在测试时,我只看到了一个 [1] 记录,现在我看到了完整的对象,谢谢

标签: mysql node.js sequelize.js


【解决方案1】:

我使用的是 MSSQL 方言,返回结果是一行新创建的数据。访问对象键“id”将向您显示上次使用的增量 id。

.then( function ( x ) {

    //x = new created row
    response.json( x.id );

} );

【讨论】:

  • 也适用于 MySQL。
【解决方案2】:

实际上,promise 函数返回新创建的行,但由于某种原因,我只能在控制台上看到 [1],现在我看到了对象。

.then( function ( x ) {

    //x = new created row
    response.json( x );

} );

【讨论】:

  • 那么当你使用create时,它返回了表上的自增主键? Sequelize 不断为我的所有插入返回 '0'
  • 您是否将autoIncrement: true 添加到您的id 属性中
【解决方案3】:

【讨论】:

  • 你也可以使用.then (anything => {sequelize.query('SELECT LAST_INSERT_ID() AS lastId', {type: Sequelize.QueryTypes.SELECT}) .then(id => {res.json({id: id[0].lastId}) })
  • 我编辑了 github 答案,现在你有一个标准的 res.json() 来了解如何。 router.post("/link", (req, res) => { const rowData = { autoincrementId: req.body.id, name: req.body.name } yourModel.create(rowData) .then(row => { sequelize.query('SELECT @@IDENTITY', {type: Sequelize.QueryTypes.SELECT}) .then(id => console.log(id); res.json({id: id[0]['@@IDENTITY'] }) })); ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
  • 2014-09-06
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多