sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

Associations not working properly

Open abtisam opened this issue 7 years ago • 4 comments

What are you doing?

I have an existing database in which relations are not defined properly with foreign keys TableStructure I am defining association among three tables

  • ptNotesMaster

  • ptResourceTrackingMaster

  • ptEquipTrackingMaster

Index.js

'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const config = require('../../config/database.js');

// this is the object that we will return. We should map all the models in this object.
const db = {};
// Create the sequelize object.
 let sequelize;
   sequelize = new Sequelize(config.database, config.user, config.password, {
      dialect: 'mssql',
      host: config.server,
      dialectOptions: {
          encrypt: true
      },define: {
          //prevent sequelize from pluralizing table names
          freezeTableName: true
      }});
// }

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

// Read the current directory, for all the file names.
//
fs
  .readdirSync(__dirname)
  .filter(file => {
    // If the file name does not begin with '.'
    // And the filename is not 'index.js'
    // And the file extension is .js
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    
    // Import this model in sequelize and also map it to the db object.
    if (file.slice(-3) !== '.js') return;
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;

    });

// All the models define an assiciate method that expects to get
// the models object and then defines relations.
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

ptNotesMaster Model

module.exports = (sequelize, DataType) => {
    const ptNotesMaster = sequelize.define('ptNotesMaster', {
        // attributes
        ID: {
            type: DataType.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        TimeEntryID: {
            type: DataType.UUID,
            allowNull: true,
            // references: {
            //     model: EquipTrackingMaster,
            //     key: 'EquipmentEntryID'
            // }
        },
        ResourceID: {
            type: DataType.UUID,
            allowNull: true,
            // references: {
            //     model: ResourceMaster,
            //     key: 'ResourceID'
            // }
        },
        ...
        DateCreated: {
            type: DataType.DATE,
            allowNull: true
        }
    }, {
            timestamps: false,
        });
        ptNotesMaster.associate = (models) => {
            ptNotesMaster.belongsTo(models.ptEquipTrackingMaster, {foreignKey: 'TimeEntryID'});
            ptNotesMaster.belongsTo(models.ptResourceMaster, {foreignKey: 'ResourceID'});
    };
    return ptNotesMaster;
}   

ptResourceTrackingMaster Model


module.exports = (sequelize, DataType) => {
    const ptResourceTrackingMaster = sequelize.define('ptResourceTrackingMaster', {
        // attributes
        ResourceID: {
            type: DataType.UUID,
            primaryKey: true
        },
        EmployeeName: {
            type: DataType.STRING,
            allowNull: true
        }
    }, {
            timestamps: false,
        });
        ptResourceTrackingMaster.associate = (models) => {
            ptResourceTrackingMaster.hasMany(models.ptNotesMaster, {foreignKey: 'ResourceID'});
        };
        return ptResourceTrackingMaster;
}

ptEquipTrackingMaster Model

module.exports = (sequelize, DataType) => {
    const ptEquipTrackingMaster = sequelize.define('ptEquipTrackingMaster', {
        // attributes
        EquipmentEntryID: {
            type: DataType.UUID,
            primaryKey: true
        },
        EquipmentCode: {
            type: DataType.STRING,
            allowNull: true
        },
        EquipmentDesc: {
            type: DataType.STRING,
            allowNull: true
        }
    }, {
            timestamps: false,
        });
        ptEquipTrackingMaster.associate = (models) => {
            ptEquipTrackingMaster.hasMany(models.ptNotesMaster, {constraints: false}, {foreignKey: 'EquipmentEntryID'});
        };

        return ptEquipTrackingMaster;
}

Error

Error: ptNotesMaster.belongsTo called with something that's not a subclass of Sequelize.Model
    at Function.<anonymous> (D:\QaviTech\Development\hypeteq\node_modules\sequelize\lib\associations\mixin.js:93:13)
    at Function.ptNotesMaster.associate (D:\QaviTech\Development\hypeteq\models\SequelizeModels\ptNotesMaster.js:120:27)
    at Object.keys.forEach.modelName (D:\QaviTech\Development\hypeteq\models\SequelizeModels\index.js:86:19)
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (D:\QaviTech\Development\hypeteq\models\SequelizeModels\index.js:82:17)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (D:\QaviTech\Development\hypeteq\models\notes\NotesMaster.js:191:16)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at Object.<anonymous> (D:\QaviTech\Development\hypeteq\routes\notes.js:1:77)
    at Module._compile (internal/modules/cjs/loader.js:701:30)

Environment

Dialect:

  • [ ] mssql

Database version: SQLServer 2014 Sequelize version: 5.9.2 Node Version: 10.15.3 OS: Windows 10

abtisam avatar Jul 06 '19 11:07 abtisam

Looks like you have a typo, at one point you have ptResourceTrackingMaster while at the other you have ptResourceMaster...

papb avatar Jul 07 '19 03:07 papb

Just posting this around on all these similar issues; I ran into this error because i was importing my Models from another folder i.e. the file where my model was defined was importing sequelize from a different node_modules. This meant that the instanceof check was false because, even though my models WERE inheriting from Model from sequelize - it was a different class, technically (with all the same properties and attributes).

You can think of a foo instanceof MyClass check as comparing the prototype of foo all the way up the chain e.g. foo.__proto__ === MyClass.prototype, foo.__proto__.__proto__ === MyClass.prototype etc. until either __proto__ is null (in which case instanceof = false) or the === equality check is true (in which case instanceof = true). So this is why a different instance of the Sequelize.Model.prototype object would return false for an instanceof check.

This is a pretty unique scenario so I solved it by symlinking the node_modules from my database project to my "shared code" project. Just wanted to post this in case anybody else was doing a similar thing, in an attempt to save somebody from a couple of hours of WTFing.

peabnuts123 avatar Apr 14 '20 23:04 peabnuts123

@peabnuts123 I have a project that defines some models as a separate npm package. When I import those models in my project and start my application, I get an error when it calls .associate:

Error: ModelNameGoesHere.hasMany called with something that's not a subclass of Sequelize.Model

ModelNameGoesHere is a model that is defined in a separate npm package. That is, it comes from

import ModelNameGoesHere from 'some-separate-npm-package'

When I copy the code from the package into my application, the problem goes away.

Is there any solution to this?

nbkhope avatar May 19 '21 01:05 nbkhope

@peabnuts123 for your interest, I created an issue for the problem:

https://github.com/sequelize/sequelize/issues/13280

nbkhope avatar May 19 '21 02:05 nbkhope