【问题标题】:How to get last inserted IDS of multiple insert in Knex.js?如何在 Knex.js 中获取多个插入的最后插入的 IDS?
【发布时间】:2019-10-23 23:36:27
【问题描述】:

我需要在一次插入多条记录时获取所有最后插入的 IDS,但现在我只得到一个 ID。

const data = await querybuilder('surveyresponse').insert(varList)

输出:

[183]

预期输出:

[183,184,185]

【问题讨论】:

    标签: mysql node.js query-builder knex.js


    【解决方案1】:

    MySQL 本身不返回该信息,因此 Knex.js 也不返回。来自文档:

    // Returns [2] in "mysql", "sqlite"; [2, 3] in "postgresql"
    knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], ['id']).into('books')
    

    您可以使用多个查询(不是最有效的方式):

    const data = await Promise.all(varList.map(item => querybuilder('surveyresponse').insert(item)
    ))
    

    其他帖子提到LAST_INSERT_ID()获取最后一个,这样你就可以得到间隔,但这在高并发时风险很大并且容易出错。

    猜你喜欢
    • 2014-01-09
    • 2019-11-21
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2016-05-28
    相关资源
    最近更新 更多