首页 > 解决方案 > Sequelize TypeScript:如果它不是模型属性的一部分,如何在范围的`where`条件中使用`createdAt`?

问题描述

我尝试将 Sequelize 与 TypeScript 一起使用。我从官方文档 TypeScript 部分复制代码,如下所示:


// These are all the attributes in the User model
interface UserAttributes {
  id: number;
  name: string;
  preferredName: string | null;
}

interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}

class User extends Model<UserAttributes, UserCreationAttributes>
  implements UserAttributes {
  public id!: number; 
  public name!: string;
  public preferredName!: string | null;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

但是,当我初始化用户表时,我想定义一个默认范围,比如字段updatedAt必须满足一些条件:

  User.init(userTableAttributes,
    {
      tableName: "user",
      sequelize,
      paranoid: true,
      defaultScope: {
        where: {
          updatedAt: {
            [Op.eq]: null
          }
        }
      }
    }
  );

但是这段代码是错误的,似乎是因为updatedAt未定义的字段UserAttributes

那么我该如何解决这个问题呢?我只想出一种方法:定义updatedAt字段UserAttributes?但这没有任何意义,因为我认为UserAttributes唯一的包括业务属性,对吧?

标签: node.jstypescriptsequelize.js

解决方案


我发现如果我添加了,它会在查询字符串中paranoid自动添加条件deletedAt is NULL


推荐阅读