Ahmad ul hoq Nadim
Ahmad ul hoq Nadim

Reputation: 378

Sequelize hasMany is working fine but the inverse relation is not working

I am trying to work with mysql relations in Node Js(express Js) using Sequelize.

User.hasMany(Post); work just fine, but when i try to inverse it in Post model like: Post.belongsTo(User);

got this error: throw new Error(${source.name}.${_.lowerFirst(Type.name)} called with something that's not a subclass of Sequelize.Model);

Error: post.belongsTo called with something that's not a subclass of Sequelize.Model

User model like:

const Sequelize = require('sequelize');
const db = require('../config/db');

const Post = require('./Post');

const User = db.define('user', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        notNull: true,
        primaryKey: true
    },
    name: {
        type: Sequelize.STRING,
        notNull: true
    },
    email: {
        type: Sequelize.STRING,
        notNull: true
    },
    password: {
        type: Sequelize.STRING,
        notNull: true
    }

});

User.hasMany(Post);

module.exports = User;

And Post model like:

const Sequelize = require('sequelize');
const db = require('../config/db');

const User = require('./User');

const Post = db.define('post', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        notNull: true,
        primaryKey: true
    },

    title: {
        type: Sequelize.STRING,
        notNull: true
    },
    description: {
        type: Sequelize.TEXT,
        notNull: true
    },
    author: {
        type: Sequelize.STRING,
        notNull: true
    }
});

Post.belongsTo(User);

module.exports = Post;

How can i solve this problem? Thanks everyone...

Upvotes: 1

Views: 2355

Answers (1)

Anatoly
Anatoly

Reputation: 22783

You should correct your model definition exports as functions and define associate function in each model definition function like this and call it all after all models are registered in some module like database.js:

user.js

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('user', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        notNull: true,
        primaryKey: true
    },
   ...

  User.associate = function (models) {
    User.hasMany(models.Post)
  }

post.js

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('post', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        notNull: true,
        primaryKey: true
    },
  ...
  Post.associate = function (models) {
    Post.belongsTo(models.User)
  }

Upvotes: 1

Related Questions