I am currently in the process of constructing table models using sequelize along with typescript.
Here is an example of one of my models:
'use strict';
import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'sequelize';
module.exports = (sequelize: any, DataTypes: any) => {
class Package extends Model<InferAttributes<Package>, InferCreationAttributes<Package>> {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
declare id: CreationOptional<number>;
declare packageName: string;
declare price: number;
declare duration: Date;
static associate(models: any) {
Package.hasMany(models.Payment);
}
}
Package.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true,
field: 'package_id'
},
packageName: {
type: DataTypes.STRING,
allowNull: false,
field: 'package_name'
},
price: {
type: DataTypes.INTEGER,
allowNull: false
},
duration: {
type: DataTypes.DATE,
allowNull: false
},
}, {
sequelize,
modelName: 'Package',
});
return Package;
};
I am trying to establish a one-to-many relationship with the payments table (each payment should be linked to a package id).
static associate(models: any) {
Payment.belongsTo(models.Package,({foreignKey: 'package_id'}));
}
However, I have noticed that when setting up the association in this manner, it results in two columns referencing the package_id
in the payments table. If I remove one of the definitions, it functions correctly, but I am unsure if this could potentially cause issues down the line. Any insights into why this behavior is occurring?
The desired outcome is to have just one column.