模型的配置

影响Sequelize列名的处理方式:

  1. class Bar extends Model {}
  2. Bar.init({ /* bla */ }, {
  3. // options
  4. // 模型名。本模型将以该名称存储在`sequelize.models`中。
  5. // 默认为类的名称,即在这种情况下为`Bar`。 这将控制自动生成的`foreignKey`的名称和关联命名
  6. modelName: 'bar',
  7. // 不要添加时间戳属性 (updatedAt, createdAt) 默认为true
  8. timestamps: false,
  9. // 不实际删除数据库记录,而是设置一个新 deletedAt 属性,其值为当前日期
  10. // `paranoid` 仅在 `timestamps` 启用时可用
  11. paranoid: true,
  12. // 自定义三个时间戳字段
  13. // 必须timestamps,才能设置createdAt 和 updatedAt
  14. // 必须paranoid为true时,才能设置deletedAt
  15. // 值可以为自定义的字段名,或者布尔值表示是否使用
  16. createdAt: 'created_at',
  17. updatedAt: 'updated_at',
  18. deletedAt: 'deleted_at',
  19. // 自动设置字段为蛇型命名规则,默认为false
  20. // 不会覆盖已定义的字段选项属性
  21. underscored: true,
  22. // 禁止修改表名,
  23. // 默认为false,sequelize会自动将所有传递的模型名称转换为复数形式。
  24. // 设置为true,则数据库的表名和Model定义的保持一致。
  25. freezeTableName: true,
  26. // 定义表名,会覆盖define定义的表名
  27. tableName: 'custom_table_name',
  28. // 启用乐观锁定。启用后,sequelize将向模型添加版本计数属性,并在保存旧实例时引发 `OptimisticLockingError` 错误。
  29. // 设置为`true`或使用要启用的属性名称的字符串。
  30. version: true,
  31. // Sequelize 实例,传入sequelize实例
  32. sequelize,
  33. })

时间戳

默认情况下,Sequelize 会自动为模型添加createdAt和updatedAt,以记录数据何时进入数据库,以及数据最后更新时间。

请注意,如果使用的是Sequelize迁移,则需要将createdAt和updatedAt字段添加到迁移定义中:

  1. module.exports = {
  2. up(queryInterface, Sequelize) {
  3. return queryInterface.createTable('my-table', {
  4. id: {
  5. type: Sequelize.INTEGER,
  6. primaryKey: true,
  7. autoIncrement: true,
  8. },
  9. // Timestamps
  10. createdAt: Sequelize.DATE,
  11. updatedAt: Sequelize.DATE,
  12. })
  13. },
  14. down(queryInterface, Sequelize) {
  15. return queryInterface.dropTable('my-table');
  16. },
  17. }

如果不希望在模型上使用时间戳,或只需要一些时间戳,或者正在使用数据库现有的其它列,请直接进入配置以查看操作。