首页 > 解决方案 > “id”列中的 Sequelize Typescript 空值违反非空约束

问题描述

背景

我最近正在使用Sequelize-Typescript设置一个数据库表,并使用这个 ORM 来帮助我进行数据库操作。

因此,我创建了一个名为uma_tbl_users以下代码段的表:


interface UserInterface {

  id: number;

  ... Other attributes...  


}

@Table(
  {
    tableName    : 'uma_tbl_users',
    timestamps   : false,
    underscored  : true,
    schema       : 'po_uma'
  }
)
class User extends Model implements UserInterface {

  @Column({
    autoIncrement: true,
    primaryKey: true,
    field: "user_id",
    type: DataTypes.BIGINT
  })
  id!: number;

  ... Other Implemented Attributes from the interface

}

创建此表后,我对其他表执行相同操作并以强制模式运行 Sequelize Database Syncer。

问题

当我运行代码来运行该表的CREATE数据语句时,我总是收到以下错误:

SequelizeDatabaseError: null value in column \"user_id\" violates not-null constraint

但奇怪的是,这个问题只发生在这张桌子上。其他所有表都可以正常工作。而且我已经确保没有验证会干扰 create 语句。

这是我的创建声明:

    const execution: User = await User.create({
      role_id: request.role,
      email: request.email,
      phone: request.phone,
      password: request.password
    });

    return execution;

我已经尝试过什么?

  1. 我试过使用@AutoIncrement@PrimaryKey注释而不是在里面加载所有选项@Column,但问题仍然存在。
  2. 我尝试使用重新同步数据库,sync({ force: true })但问题仍然存在。
  3. 我正在使用一种野蛮的方式,我忽略了上面的问题,只是使用“获取最新的 ID,并将 ID 放入 create 语句”,奇怪的是,当我返回创建的模型时,而不是返回插入的 ID,它返回最后一行索引的计数。(假设我有 6 个数据uma_tbl_users,ID 将返回 6 而不是我必须插入的)
  4. 我已经查看了关于这个问题的 Github 和 Stackoverflow 线程,我总是收到“你必须强制数据库同步”,但这个解决方案不能解决我的问题。
  5. 我已经确保自动增量运行良好。我直接在数据库中测试了一个 create 语句,它会自动生成 ID。

我目前正在使用什么?

框架/语言/数据库

  1. 打字稿 4.2.4 (@types/node 14.14.41)
  2. 快递 4.17.1 (@types/express 4.17.11)
  3. PostgreSQL 12.3

依赖项(npm 6.9.0)

  1. 续集 6.6.2
  2. Sequelize-Typescript 2.1.0
  3. 第 8.6.0 页
  4. pg-hstore 2.3.3

标签: typescriptpostgresqlexpresssequelize-typescript

解决方案


您可能在播种此特定表时自己提供主键。

自定义 PK 和 AutoIncrement 设置为 true 的表不应使用显式设置的主键作为种子。

只需播种其他列。Sequelize-Typescript 将自行输入主键。


推荐阅读