This is my code:
public getSpecs = async (req: Request, res: Response, next: NextFunction) => {
try {
const MasterSpecCategory = models[res.locals.project].master_spec_category;
const MasterSpec = models[res.locals.project].master_spec;
MasterSpecCategory.hasMany(MasterSpec, { as: 'values', foreignKey: 'spec_category_id' });
const get_specs = await MasterSpecCategory.findAll({
include: {
model: MasterSpec,
as: 'values'
},
});
return SuccessResponse(res, req.t('COMMON.OK'), get_specs);
} catch (err) {
next(err);
}
};
The error in postman:
{
"status": 500,
"success": false,
"data": 500,
"message": "You have used the alias values in two separate associations. Aliased associations must have unique aliases."
}
import { DataTypes, Sequelize } from 'sequelize';
module.exports = (sequelize: Sequelize) => {
return sequelize.define(
'master_spec_category',
{
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
},
name: {
type: DataTypes.STRING(100),
allowNull: true
},
key: {
type: DataTypes.STRING(50),
allowNull: true
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
icon: {
type: DataTypes.STRING(100),
allowNull: true
},
type: {
type: DataTypes.ENUM('int', 'option'),
allowNull: true
},
status: {
type: DataTypes.ENUM('hide','disable', 'enable' ),
allowNull: true
},
},
{
tableName: 'master_spec_category',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
]
}
);
}
import { DataTypes, Sequelize } from 'sequelize';
module.exports = (sequelize: Sequelize) => {
return sequelize.define(
'master_spec',
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
spec_category_id: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'master_spec_category',
key: 'id',
},
},
disp_order: {
type: DataTypes.INTEGER,
allowNull: true
},
name: {
type: DataTypes.STRING(100),
allowNull: true
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
icon: {
type: DataTypes.STRING(200),
allowNull: true
},
status: {
type: DataTypes.ENUM('hide','disable', 'enable' ),
allowNull: true
},
},
{
tableName: 'master_spec',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "id" },
]
},
{
name: 'fk_master_spec_master_spec_category',
using: 'BTREE',
fields: [
{ name: 'id' }
],
},
]
}
);
};
I think I had done all the things right, but still it giving that error on second hit in postman.
Is there anyway to solve this??!!
You shouldn't register associations every time you are about to execute Sequelize queries against models (hasMany
in this case). Just register them once at the app startup.
Look at my other answer to get an idea how it might look like.