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.
Item
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.
Also on making a select query on items. like below.
const items = await Item.findAll({include: [Metric]});
I get below error