如何以正确的方式使用模型 - sequelize with typescript

How to use the Model in the currect way - sequelize with typescript

这是我的续集模型 -

import { BuildOptions, DataTypes, Model, Sequelize } from "sequelize";

import { IDBUserAttributes } from "./shared/db-table";

    interface UserModel extends Model<IDBUserAttributes>, IDBUserAttributes {}
    
    class User extends Model<UserModel, IDBUserAttributes> {}
    
    type UserStatic = typeof Model & {
      new (values?: object, options?: BuildOptions): UserModel;
    };
    
    const UserFactory = (sequelize: Sequelize): UserStatic => {
      return <UserStatic>sequelize.define("users", {
        id: {
          type: DataTypes.INTEGER.UNSIGNED,
          autoIncrement: true,
          primaryKey: true,
          unique: true,
          allowNull: false,
        },
        email: {
          type: DataTypes.STRING(320),
          allowNull: false,
          unique: true,
        },
        username: {
          type: DataTypes.STRING(26),
          allowNull: false,
        },
        password: {
          type: DataTypes.STRING(255),
          allowNull: false,
        },
        createdAt: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
        },
        updatedAt: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
        },
      });
    }
    
    export {
      UserModel,
      User,
      UserFactory,
      UserStatic,
    }

我想在控制器中使用模型。例如像这样 - User.create() 或任何其他方法。

如何获取模型? ..................................................... ..................................................... .....................................

我认为你在混合使用 sequelize js 和 sequelize ts。我从未将 sequelize 与 vanilla js 一起使用,但我认为你不需要 UserFactory。 class 应该足以实例化您的模型并创建它。

一个简单的 class 应该是这样的:

@Table({ modelName: 'users' })
export class UserModel extends Model {
  @Column({ primaryKey: true, allowNull: false, autoIncrement: true, type: DataTypes.INTEGER })
  idUser: number;

  @Column({ type: DataTypes.STRING })
  firstName: string;

  @Column({ type: DataTypes.STRING })
  lastName: string;
}

您可以使用 @Column 将所有列描述为 class 的属性,并为此注释提供一些参数。

然后你只需要在你的代码中导入(或根据你的框架注入)你就可以使用class.

的所有方法了

在我的例子中它看起来像

UserModel.create(params)

有关更多详细信息,您可以在此处找到文档: https://github.com/RobinBuschmann/sequelize-typescript#model-definition