typescript - “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;
我已经尝试过什么?
- 我试过使用
@AutoIncrement
和@PrimaryKey
注释而不是在里面加载所有选项@Column
,但问题仍然存在。 - 我尝试使用重新同步数据库,
sync({ force: true })
但问题仍然存在。 - 我正在使用一种野蛮的方式,我忽略了上面的问题,只是使用“获取最新的 ID,并将 ID 放入 create 语句”,奇怪的是,当我返回创建的模型时,而不是返回插入的 ID,它返回最后一行索引的计数。(假设我有 6 个数据
uma_tbl_users
,ID 将返回 6 而不是我必须插入的) - 我已经查看了关于这个问题的 Github 和 Stackoverflow 线程,我总是收到“你必须强制数据库同步”,但这个解决方案不能解决我的问题。
- 我已经确保自动增量运行良好。我直接在数据库中测试了一个 create 语句,它会自动生成 ID。
我目前正在使用什么?
框架/语言/数据库
- 打字稿 4.2.4 (@types/node 14.14.41)
- 快递 4.17.1 (@types/express 4.17.11)
- PostgreSQL 12.3
依赖项(npm 6.9.0)
- 续集 6.6.2
- Sequelize-Typescript 2.1.0
- 第 8.6.0 页
- pg-hstore 2.3.3
解决方案
您可能在播种此特定表时自己提供主键。
自定义 PK 和 AutoIncrement 设置为 true 的表不应使用显式设置的主键作为种子。
只需播种其他列。Sequelize-Typescript 将自行输入主键。
推荐阅读
- c - C 中的 fork()。我需要解释这段代码
- pre-commit-hook - 使用 Husky 时出现预提交错误“找不到模块 - npx-cli.js”
- c# - 具有标识的 Blazor 应用程序不会创建帐户控制器
- excel - 防止价值重复
- firebase - Flutter Firebase 身份验证 - 注销和登录后生成的新匿名用户
- python - Django“用户”对象没有属性“电话”
- firebase - 存储为整数与字符串大小
- flutter - 无法通过 ScanStreamTransformer 正确检索模型
- postgresql - pgAdmin 中的导入/导出对话框消失
- matlab - 在频谱分析 MATLAB 中查找噪声频率区间