【问题标题】:NodeJs : Sequelize (Version - 5+) N:M association is not workingNodeJs:Sequelize(版本 - 5+)N:M 关联不起作用
【发布时间】:2020-06-16 03:11:32
【问题描述】:

我遇到了一个与 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)

查找下面的代码

//models/database.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'
                            });

//models/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"));

//models/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"));

//models/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"));

【问题讨论】:

  • 执行 Batch.belongsToMany(User ... ?

标签: node.js sequelize.js sequelize-typescript


【解决方案1】:

我找到了一个解决方案,而且效果很好。

我从models/Batch.ts 中删除了这一行Batch.belongsToMany(User, {through:{model: UserBatch}, sourceKey:"id", foreignKey: "batch_id"}); 并添加到 models/User.ts.

User.belongsToMany(Batch, {through:{model:UserBatch}, sourceKey:"id", foreignKey: "user_id"});
Batch.belongsToMany(User, {through:{model: UserBatch}, sourceKey:"id", foreignKey: "batch_id"});

请查看完整代码//models/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
  }
);

User.belongsToMany(Batch, {through:{model:UserBatch}, sourceKey:"id", foreignKey: "user_id"});
Batch.belongsToMany(User, {through:{model: UserBatch}, sourceKey:"id", foreignKey: "batch_id"});

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

【讨论】:

    【解决方案2】:

    你在某个地方运行过这样的东西吗?您似乎在使用类而不是对模型进行续集..因此错误“使用不是 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,语法不同,但想法是一样的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-13
      • 2018-10-02
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多