简体   繁体   中英

Sequelize: "Model A is not associated to Model B"

I have issue: "is not associated to". I want to have one to many association. Here is my code Index.js

  fs.readdirSync(__dirname)
  .filter(file => {
    return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});
db.Sequelize = Sequelize;
db.sequelize = sequelize;
module.exports = db;

Here is course.js

module.exports = (sequelize, Sequelize) => {
  const Course = sequelize.define(
    'course',
    {
      idCourse: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        field: 'idcourse',
      },
      nameOfCourse: {
        type: Sequelize.STRING,
        field: 'nameofcourse',
      },
      idLevel: {
        type: Sequelize.INTEGER,
        field: 'idlevel',
      },
      idTypeOfCourse: {
        type: Sequelize.INTEGER,
        field: 'idtypeofcourse',
      },
      startDate: {
        type: Sequelize.DATE,
        field: 'startdate',
      },
      endDate: {
        type: Sequelize.DATE,
        field: 'enddate',
      },
      fee: {
        type: Sequelize.BIGINT,
        field: 'fee',
      },
      isDeleted: {
        type: Sequelize.BOOLEAN,
        field: 'isdeleted',
      },
    },
    {
      freezeTableName: true,

      timestamps: false,

      createdAt: false,

      updatedAt: false,
    }
  );
  Course.associate = function (models) {
    models.course.belongsToMany(models.bill, {
      through: models.billinfo,
      as: 'bill',
      foreignKey: 'idCourse',
    });
    models.course.belongsTo(models.typeofcourse, {
      foreignKey: 'idTypeOfCourse',
      sourceKey: 'idCourse',
      as: 'typeofcourse',
    });
  };
  return Course;
};

Here is TypeOfCourse.js

module.exports = (sequelize, Sequelize) => {
  const TypeOfCourse = sequelize.define(
    'typeofcourse',
    {
      idTypeOfCourse: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        field: 'idtypeofcourse',
      },
      nameOfType: {
        type: Sequelize.STRING,
        field: 'nameoftype',
      },
      language: {
        type: Sequelize.STRING,
        field: 'language',
      },
      tags: {
        type: Sequelize.ARRAY(Sequelize.TEXT),
        field: 'tags',
      },
      isDeleted: {
        type: Sequelize.BOOLEAN,
        field: 'isdeleted',
      },
    },
    {
      freezeTableName: true,

      timestamps: false,

      createdAt: false,

      updatedAt: false,
    }
  );
  TypeOfCourse.associate = function (models) {
    models.typeofcourse.hasMany(models.course, {
      foreignKey: 'idTypeOfCourse',
      as: 'course',
    });
  };
  return TypeOfCourse;
};

In course.controller.js, I define function findAll Course and want to display info about typeOfCourse

exports.findAll = (req, res) => {
  Course.findAll({
    include: [
      {
        model: TypeOfCourse,
        as: 'typeofcourse',
        through: { attributes: [] },
      },
    ],
  })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || 'Some error occurred while retrieving course.',
      });
    });
};

But when i send request to get course. This message responed:

{
    "message": "typeofcourse is not associated to course!"
}

Where I wrong and how to fix this error. Thank you so much.

You can use the hasMany association, it will Create an N:M association with a join table

Course.hasMany(TypeOfCourse, {
          foreignKey: { name: 'idCourse' },
          targetKey: 'idCourse',
          constraints: false,
          as: 'typeOfCourses',
        }),
    ```

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM