NodeJs 的 Sequelize 中 autoIncrement 是如何工作的?

编程入门 行业动态 更新时间:2024-10-03 04:36:37

NodeJs 的 Sequelize 中 autoIncrement 是如何<a href=https://www.elefans.com/category/jswz/34/1771444.html style=工作的?"/>

NodeJs 的 Sequelize 中 autoIncrement 是如何工作的?

Sequelize 的文档并没有对

autoIncrement
进行太多说明。它仅包括以下示例:

// autoIncrement can be used to create auto_incrementing integer columns
incrementMe: { type: Sequelize.INTEGER, autoIncrement: true }

基于这个例子,我有以下代码:

db.define('Entries', {
    id: {
        type: Seq.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    title: {
        type: Seq.STRING,
        allowNull: false
    },
    entry: {
        type: Seq.TEXT,
        allowNull: false
    }
}

现在,当我想创建一个条目时,我想做这样的事情:

models.Entry.create({title:'first entry', entry:'yada yada yada'})

但是,当我执行该代码时,我收到数据库错误:

“id”列中的空值违反了非空约束

我假设 Sequelize 会为我放入整数或定义数据库表来自行完成此操作。显然不是?我在这里缺少什么来确保 id 自动递增和填充?

非常感谢。

回答如下:

通常 Sequelize.js 会根据数据库进行自适应。所以autoincrement属性对应的是PostgreSQL中的serial类型。

我已经使用过 Sequelize,我记得你不需要指定 id 作为主键。 Sequelize 会为你做的。

尝试不添加 id 属性,看看 Sequelize 是否不会为你添加它。

更多推荐

NodeJs 的 Sequelize 中 autoIncrement 是如何工作的?

本文发布于:2024-05-31 06:57:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771392.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:工作   NodeJs   Sequelize   autoIncrement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!