midwayjs报错:Model not initialized: Member \"getTableName\" cannot be called. \"User\" needs to be added to a Sequelize instance

声明:作者声明此文章为原创,未经作者同意,请勿转载,若转载,务必注明本站出处,本平台保留追究侵权法律责任的权利。
全栈老韩
全栈工程师,擅长iOS App开发、前端(vue、react、nuxt、小程序&Taro)开发、Flutter、React Native、后端(midwayjs、golang、express、koa)开发、docker容器、seo优化等。

问题

Model not initialized: Member "getTableName" cannot be called. "User" needs to be added to a Sequelize instance

出现错误的地方:

async getAllPosts(body: any) {
    const { pageSize, pageIndex, userId } = body;
    let query: Object = {};
    query["offset"] = (pageIndex !== undefined && pageIndex !== null) ? ((pageIndex - 1) * (pageSize || 10)) : 0;
    query["limit"] = (pageSize !== undefined && pageSize !== null) ? pageSize : 10;
    if (userId !== undefined && userId !== null) {
      query["where"] = {
        user_id : userId
      };
    }

    query["include"] = [User]; 

    let result: { rows: HuntingPostForm[]; count: number };
    try {
      result = await this.huntingPostModel.findAndCountAll(query)
    } catch (error) {
      throw new CommonException(StatusCode.SYS_ERROR, error.message);
    }
}

解决方法:

https://github.com/sequelize/sequelize-typescript/issues/686 只能参考

https://github.com/sequelize/sequelize-typescript#how-to-use-associations-with-repository-mode 可以解决
就是Repository方式的include中,必须还是Repository类型

query["include"] = [this.huntingRoleModel]; // [this.userModel, this.huntingRoleModel]

暂无评论,快来发表第一条评论吧