0

I am working on an electron app and for the database, I am using sqlite3 along with sequelize. I want to establish a one-to-many relationship between two of the following models.

  1. Item

  2. Metric Metrics can be liters/kilograms/units and an item can be measured in any of these metrics. So following is how I have declared the Item model.

    const { Model, DataTypes } = require("sequelize"); const sequelize = require("../database/db"); const Metric = require("./metricModel"); class Item extends Model {}

    Item.init( { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true, }, name: { type: DataTypes.STRING, allowNull: false, }, metricId: { type: DataTypes.INTEGER, allowNull: false, references: { model: "metrics", key: "id", }, }, available: { type: DataTypes.FLOAT, defaultValue: 0, }, incoming: { type: DataTypes.FLOAT, defaultValue: 0, }, }, { sequelize, tableName: "items", freezeTableName: true, } ); Item.associate = (models) => { Item.belongsTo(models.Metric, { foreignKey: "metricId" }); }; module.exports = Item;

And following is how I have declared the Metric

const { Model, DataTypes } = require("sequelize");
const sequelize = require("../database/db");
const Item = require("./itemModel");

class Metric extends Model {}

Metric.init(
  {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true,
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
    },
    description: {
      type: DataTypes.STRING(10000),
    },
  },
  {
    sequelize,
    tableName: 'metrics', freezeTableName: true 
  }
);
Metric.associate = function (models) {
  Metric.hasMany(models.Item, { foreignKey: "metricId" });
};
module.exports = Metric;

But in the logs, I can't see any association getting created. enter image description here

Also on making a select query on items. like below.

const items = await Item.findAll({include: [Metric]});

I get below error

enter image description here

  • Did you register all models and only after that all associations? Please see my answer https://stackoverflow.com/a/61710568/1376618 – Anatoly Dec 25 '21 at 09:29

1 Answers1

0

My bad, there was a duplicate column in my items model and since during debugging the table named item was present beforehand, it was working fine. If you encounter this issue, make sure all your tables are declared properly.