Constraints & Circularities - 约束 & 循环

在表之间添加约束意味着使用 sequelize.sync 时必须在数据库中以一定顺序创建表. 如果 Task 具有对 User 的引用,则必须先创建 User 表,然后才能创建 Task 表. 有时这可能会导致循环引用,而 Sequelize 无法找到同步的顺序. 想象一下文档和版本的情况. 一个文档可以有多个版本,为方便起见,文档引用了其当前版本.

  1. const { Sequelize, Model, DataTypes } = require("sequelize");
  2. class Document extends Model {}
  3. Document.init({
  4. author: DataTypes.STRING
  5. }, { sequelize, modelName: 'document' });
  6. class Version extends Model {}
  7. Version.init({
  8. timestamp: DataTypes.DATE
  9. }, { sequelize, modelName: 'version' });
  10. Document.hasMany(Version); // 这会将 documentId 属性添加到 version 中
  11. Document.belongsTo(Version, {
  12. as: 'Current',
  13. foreignKey: 'currentVersionId'
  14. }); // 这会将 currentVersionId 属性添加到 document 中

但是,不幸的是,上面的代码将导致以下错误:

  1. Cyclic dependency found. documents is dependent of itself. Dependency chain: documents -> versions => documents

为了减少这种情况,我们可以将 constraints: false 传递给关联之一:

  1. Document.hasMany(Version);
  2. Document.belongsTo(Version, {
  3. as: 'Current',
  4. foreignKey: 'currentVersionId',
  5. constraints: false
  6. });

这将使我们能够正确同步表:

  1. CREATE TABLE IF NOT EXISTS "documents" (
  2. "id" SERIAL,
  3. "author" VARCHAR(255),
  4. "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  5. "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  6. "currentVersionId" INTEGER,
  7. PRIMARY KEY ("id")
  8. );
  9. CREATE TABLE IF NOT EXISTS "versions" (
  10. "id" SERIAL,
  11. "timestamp" TIMESTAMP WITH TIME ZONE,
  12. "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  13. "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  14. "documentId" INTEGER REFERENCES "documents" ("id") ON DELETE
  15. SET
  16. NULL ON UPDATE CASCADE,
  17. PRIMARY KEY ("id")
  18. );

不受限制地强制执行外键引用

有时,你可能希望引用另一个表,而不添加任何约束或关联. 在这种情况下,你可以将引用属性手动添加到架构定义中,并标记它们之间的关系.

  1. class Trainer extends Model {}
  2. Trainer.init({
  3. firstName: Sequelize.STRING,
  4. lastName: Sequelize.STRING
  5. }, { sequelize, modelName: 'trainer' });
  6. // 在我们调用 Trainer.hasMany(series) 之后,
  7. // Series 将会有一个 trainerId = Trainer.id 外参考键
  8. class Series extends Model {}
  9. Series.init({
  10. title: Sequelize.STRING,
  11. subTitle: Sequelize.STRING,
  12. description: Sequelize.TEXT,
  13. // 设置与 `Trainer` 的外键关系(hasMany)
  14. trainerId: {
  15. type: DataTypes.INTEGER,
  16. references: {
  17. model: Trainer,
  18. key: 'id'
  19. }
  20. }
  21. }, { sequelize, modelName: 'series' });
  22. // 在我们调用 Series.hasOne(Video) 之后,
  23. // Video 将具有 seriesId = Series.id 外参考键
  24. class Video extends Model {}
  25. Video.init({
  26. title: Sequelize.STRING,
  27. sequence: Sequelize.INTEGER,
  28. description: Sequelize.TEXT,
  29. // 设置与 `Series` 的关系(hasOne)
  30. seriesId: {
  31. type: DataTypes.INTEGER,
  32. references: {
  33. model: Series, // 可以是代表表名的字符串,也可以是 Sequelize 模型
  34. key: 'id'
  35. }
  36. }
  37. }, { sequelize, modelName: 'video' });
  38. Series.hasOne(Video);
  39. Trainer.hasMany(Series);