Problem with Relationship Sequelize

Asked

Viewed 114 times

0

I have two tables called type_agricultural_implement and agricultural_implement, in which the id of type_agricultural_implement is inside the table agricultural_implement as type_agricultural_implement_id. Thus forming a 1:M relationship.

Model - type_agricultural_implement

/* jshint indent: 2 */

module.exports = function (sequelize, DataTypes) {
  const type_agricultural_implement = sequelize.define(
    'type_agricultural_implement',
    {
      id: {
        type: DataTypes.INTEGER(5).UNSIGNED.ZEROFILL,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
      },
      description: {
        type: DataTypes.STRING(90),
        allowNull: false,
      },
    },
    {
      tableName: 'type_agricultural_implement',
    }
  );
  type_agricultural_implement.associate = (models) => {
    type_agricultural_implement.hasMany(models.agricultural_implement, {
      foreignKey: 'type_agricultural_machine_id',
    })
  }
};

Model - agricultural_implement

/* jshint indent: 2 */

module.exports = function (sequelize, DataTypes) {
  const agricultural_implement = sequelize.define('agricultural_implement', {
    agricultural_implement_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      references: {
        model: 'agricultural_machine',
        key: 'agricultural_machine_id'
      }
    },
    type_agricultural_machine_id: {
      type: DataTypes.INTEGER(5).UNSIGNED.ZEROFILL,
      allowNull: false,
      references: {
        model: 'type_agricultural_machine',
        key: 'id',
      },
    },
  }, {
    tableName: 'agricultural_implement'
  });

  agricultural_implement.associate = (models) => {
    agricultural_implement.belongsTo(models.type_agricultural_machine, { foreignKey: 'type_agricultural_machine_id' });
  };

  return agricultural_implement;
};

And as it rotates this happens

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

1 answer

0


I solved the problem, in Model agricultural_implement where there’s this part

type_agricultural_machine_id: {
      type: DataTypes.INTEGER(5).UNSIGNED.ZEROFILL,
      allowNull: false,
      references: {
        model: 'type_agricultural_machine',
        key: 'id',
      },
    },
  }, {
    tableName: 'agricultural_implement'
  });

  agricultural_implement.associate = (models) => {
    agricultural_implement.belongsTo(models.type_agricultural_machine, { foreignKey: 'type_agricultural_machine_id' });
  };

I misnamed, in the type_agricultural_machine_id was meant to be type_agricultural_implement_id, to references the same thing, assoaciação too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.