gpt4 book ai didi

postgresql - 在 Sequelize 外键中什么是可延迟的?

转载 作者:行者123 更新时间:2023-11-29 12:30:45 24 4
gpt4 key购买 nike

我正在学习 Sequelize 和模型的外键,但我不明白目的是什么 deferable field

It will create a foreign key that will check the constraints

我不明白这里的约束(限制)是什么。我应该定义它吗?我已经在官方文档上查看了代码,但没有帮助,也无法理解它的用法。如果有人帮助我理解,我将不胜感激。

最佳答案

文档提到:

A collection of properties related to deferrable constraints. It can be used to make foreign key constraints deferrable and to set the constraints within a transaction. This is only supported in PostgreSQL.

所以,这就是您在 google 上搜索 postgres foreign key deferrable 或类似内容的提示。 postgres docs say :

SET CONSTRAINTS sets the behavior of constraint checking within the current transaction. IMMEDIATE constraints are checked at the end of each statement. DEFERRED constraints are not checked until transaction commit. Each constraint has its own IMMEDIATE or DEFERRED mode.

Upon creation, a constraint is given one of three characteristics: DEFERRABLE INITIALLY DEFERRED, DEFERRABLE INITIALLY IMMEDIATE, or NOT DEFERRABLE. The third class is always IMMEDIATE and is not affected by the SET CONSTRAINTS command. The first two classes start every transaction in the indicated mode, but their behavior can be changed within a transaction by SET CONSTRAINTS.

解包:可延迟意味着您可以“延迟”外键约束的检查,直到事务结束。 (顺便说一句,事务基本上是“查询组”,它们要么全部成功,要么如果其中一个失败,则所有其他的也会回滚。)

让我们举一个人为的例子:假设您有一个 blogs 表,它有一个指向 categories 表的外键。当您插入新的博客文章时,它链接到的类别必须存在 - 否则 blogs to categories 外键约束将失败。但是......如果我们使用延迟功能,那么我们可以做这样的事情(在伪代码中):

1. Being a transaction
2. Tell postgres to use deferred foreign key constraints for this transaction
3. Insert a blog that links to the "Hello World" category (which does not yet exist)
3a. (Note this is where Postgres would normally check the foreign key constraint and fail)
4. Insert the "Hello World" Category
5. Commit the transaction
6. Because we're using the DEFERRED feature, the foreign key check
will happen now, at the end of the transaction, instead of at 3a,
and it will succeed, because "Hello Wolrd" category now exists!

长话短说,您应该省略 deferrable 键(或将其设置为 false),除非您知道自己需要它。

关于postgresql - 在 Sequelize 外键中什么是可延迟的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42494481/

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