gpt4 book ai didi

node.js - postgreSQL 表约束、sequelize 选项和 sequelize 验证之间的区别?

转载 作者:行者123 更新时间:2023-12-03 22:26:24 26 4
gpt4 key购买 nike

postgeSQL 表约束、sequelize 选项和 sequelize 验证之间的区别?

例如:

有什么区别:

 title: { type: Sequelize.STRING, allowNull: false},


 title: { type: Sequelize.STRING, validate: { notNull: true }


 CREATE TABLE mytable( username TEXT NOT NULL )

documentation 他们说:
 // setting allowNull to false will add NOT NULL to the column, which means an error will be
// thrown from the DB when the query is executed if the column is null. If you want to check that a value
// is not null before querying the DB, look at the validations section below.

为什么会从数据库中抛出错误,但约束在 Sequelize 模型定义中?为什么不直接从 sequelize 中扔掉它呢?那么模型定义的目的是什么?另一件让我感到困惑的事情是为什么我们需要来自“验证选项”的额外验证,但我们在模型中也有约束。

如果我们在 postgreSQL 表中而不是在 sequelize 模型中放置一个约束,反之亦然会发生什么?

最佳答案

我想当这个 ORM 创建表时,allowNull: false 直接转换为 NOT NULL 约束。
来自 https://sequelize.org/v5/manual/models-definition.html

// setting allowNull to false will add NOT NULL to the column, which means an error will be

// thrown from the DB when the query is executed if the column is null.


也就是说,第一个和第三个片段是等效的,前提是表是使用 ORM 创建的。
第二个代码段中的验证发生在“客户端”端(即,当您运行 JS 代码时)。如果您只有验证,但没有数据库中的约束,那么您可以设置 NULL 值,例如通过使用其他一些客户端。如果您有数据库约束,那么无论您使用什么客户端,都不能设置 NULL 值。

关于node.js - postgreSQL 表约束、sequelize 选项和 sequelize 验证之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com