node.js - NodeJs : Sequelize (Version - 5+) N:M association is not working

标签 node.js sequelize.js sequelize-typescript

我遇到了一个与 N:M 关联与 sequelize 相关的问题。
我尝试了 5 种不同的方法(参见 User.ts & Batch.ts [1]/[2]... 的代码部分)。
请在下面找到错误和代码详细信息。

使用的版本 - "sequelize": "^5.21.5"

引用:https://sequelize.org/v5/manual/associations.html#belongs-to-many-associations

我需要你的指导来解决这个问题。

低于错误

/home/priyabrata/projects/node_backend_new/node_modules/sequelize/lib/associations/mixin.js:49
      throw new Error(`${this.name}.belongsToMany called with something that's not a subclass of Sequelize.Model`);
      ^

Error: Batch.belongsToMany called with something that's not a subclass of Sequelize.Model
    at Function.belongsToMany (/home/priyabrata/projects/node_backend_new/node_modules/sequelize/lib/associations/mixin.js:49:13)

找到下面的代码

//模型/数据库.ts
import {Sequelize} from 'sequelize';
import Config from "config";
export const database = new Sequelize(
                            Config.get("DB.NAME"), 
                            Config.get("DB.USER"), 
                            Config.get("DB.PASS"),
                            {
                                host: Config.get("DB.HOST"),
                                port: 3306,
                                dialect: 'mysql'
                            });

//模型/User.ts
import { Model, DataTypes } from "sequelize";
import { database } from "./database";
import { Batch } from "./Batch"
import { UserBatch } from "./UserBatch";

export class User extends Model {

}

export interface UserInterface {
  id: number;
  firstname: string;
  lastname: string;
}

User.init(
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false
    },
    firstname: {
      type: DataTypes.STRING(100),
      allowNull: false,
      defaultValue: ''
    },
    lastname: {
      type: DataTypes.STRING(100),
      allowNull: false,
      defaultValue: ''
    }
  },
  {
    underscored: true,
    tableName: "user",
    collate: "utf8mb4_unicode_ci",
    charset : "utf8mb4",
    engine : "InnoDB",
    sequelize: database, // this bit is important
    timestamps: false
  }
);



//[1] - Not working
// User.belongsToMany(Batch, {through:{model:UserBatch}, foreignKey:"user_id"});

//[2] - Not working
// User.belongsToMany(Batch, {through:{model:UserBatch}, foreignKey:"id"});

//[3] - Not working
//User.belongsToMany(Batch, {through:{model:UserBatch}, foreignKey:"id", otherKey: "user_id"});

//[4] - Not working
// User.belongsToMany(Batch, {through:'user_batch', foreignKey:"id"});

//[5] - Not working
// User.belongsToMany(Batch, {through:'user_batch', foreignKey:"id", otherKey: "user_id"});

// Below line will create table based on the above defination
// User.sync({ force: true }).then(() => console.log("User table created"));


//模型/Batch.ts
import { Model, DataTypes } from "sequelize";
import { database } from "./database";
import { User } from "./User"
import { UserBatch } from "./UserBatch"

export class Batch extends Model {
}

export interface BatchInterface {
  id: number;
  name: string;
}


Batch.init(
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false
    },
    name: {
      type: DataTypes.STRING(100),
      allowNull: false,
      defaultValue: ''
    }
  },  {
    underscored: true,
    tableName: "batch",
    collate: "utf8mb4_unicode_ci",
    charset : "utf8mb4",
    engine : "InnoDB",
    sequelize: database, // this bit is important
    timestamps: false
  }
);

//[1] - Not working
// Batch.belongsToMany(User, {through:{model: UserBatch}, foreignKey:"batch_id"});

//[2] - Not working
// Batch.belongsToMany(User, {through:{model: UserBatch}, foreignKey:"id"});

//[3] - Not working
//Batch.belongsToMany(User, {through:{model: UserBatch}, foreignKey:"id", otherKey: "batch_id"});

//[4] - Not working
// Batch.belongsToMany(User, {through:'user_batch', foreignKey:"id"});

//[5] - Not working
// Batch.belongsToMany(User, {through:'user_batch', foreignKey:"id", otherKey: "batch_id"});

// Below line will create table based on the above defination
// Batch.sync({ force: true }).then(() => console.log("batch table created"));

//模型/UserBatch.ts
import { Model, DataTypes } from "sequelize";
import { database } from "./database";

export class UserBatch extends Model {

}

export interface UserBatchInterface {
  user_id: number;
  batch_id: number;
}

UserBatch.init(
  {
    user_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false
    },
    batch_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false
    }
  },  {
    underscored: true,
    tableName: "user_batch",
    collate: "utf8mb4_unicode_ci",
    charset : "utf8mb4",
    engine : "InnoDB",
    sequelize: database, // this bit is important
    timestamps: false
  }
);

// Below line will create table based on the above defination
// UserBatch.sync({ force: true }).then(() => console.log("user_batch table created"));

最佳答案

你在某处运行这样的东西吗??您似乎正在使用类而不是 Sequelize 模型..因此错误“用不是 Sequelize.Model 的子类的东西调用”

import { Sequelize } from 'sequelize';
import database from 'wherever that is exported';

const models = {
  User: database.import('path to where this class is'),
  UserBatch : database.import('path to where this class is'),
  Batch : database.import('path to where this class is'),
};

Object.keys(models).forEach((modelName) => {
  if ('associate' in models[modelName]) {
    models[modelName].associate(models);
  }
});

models.database= database;
models.Sequelize = Sequelize;

export default models;

然后在每个类中你可能有一个函数,上面的代码用来初始化你的类
User.associate = function (models) {
    models.User.belongsToMany(models.Batch, { through: models.UserBatch, as: 'batch', foreignKey: 'user_id' });    
  };

我意识到我使用了 javascript 并且语法不同,但想法是一样的

关于node.js - NodeJs : Sequelize (Version - 5+) N:M association is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60512291/

相关文章:

node.js - 无法在 "modelRepository"构造函数的位置 #0 注入(inject)依赖项 "GetModelService"。原因 : Cannot read property 'name' of undefined

html - Angular 组件如何使用用户定义的样式表?

node.js - 使用带有 'require' 的 Promise 来动态加载模块

javascript - 如何在 React 中反转数组

javascript - 仅从主查询中按顺序排列顺序

typescript - 将模型与 sequelize-typescript 相关联

node.js - 如何为生产级别的不同服务器动态连接具有不同凭据的数据库?

node.js - Nodejitsu - 错误 : No default engine was specified and no extension was provided

node.js - Sequelize 设置限制为最大行数

node.js - 折旧警告不允许在 AZURE 上部署应用程序,