如何使用 sequelize 重置 autoIncrement 主键? [英] How to reset autoIncrement primary key with sequelize?

查看:310
本文介绍了如何使用 sequelize 重置 autoIncrement 主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 sqlite3 作为我的数据库并使用sequelize"库来处理它.我有一个模块,想在截断它后重置 autoIncrement 主键.

I use sqlite3 as my DB and use "sequelize" library to handle it. I have a module and want to reset autoIncrement primary key after truncate it.

    var logModule = db.logModule()
    logModule.destroy({

        where:{},
        truncate: true
    })

但我发现这种方法只是清除我表中的所有记录,并没有将 autoIncrement promary key 重置为零.

But I found this way just clear all records in my table, didn't reset the autoIncrement promary key to zero.

清除我表中的所有记录后,有没有办法重置主键?

Is there any way to reset primary key after clear all records in my table?

推荐答案

你应该通过 restartIdentity: true 来销毁/截断 sequelize 中的方法.

You should pass restartIdentity: true to destroy / truncate methods in sequelize.

   models[modelName]
     .destroy({ truncate: true, restartIdentity: true })

restartIdentity - 仅与 TRUNCATE 结合使用.自动重新启动被截断表的列所拥有的序列.

restartIdentity - only used in conjunction with TRUNCATE. Automatically restart sequences owned by columns of the truncated table.

这对于由 sequelize 为 sqlite 生成的 id 字段无法按预期工作.

This does not work as expected with the id field generated by sequelize for sqlite.

你必须显式调用 SQL:

DELETE FROM `sqlite_sequence` WHERE `name` = 'table_name'

这篇关于如何使用 sequelize 重置 autoIncrement 主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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