Would be great if someone can help on this.
Already I have gone though How to implement many to many association in sequelize. Still I have question
I'm using Postgre and Express.
I have models size, item and itemsize. Refer below code.
objects are synced to db as expected. when I'm trying to add item and itemsize, I couldn't find the methods item.addxxx(), item.getxxx(), item.setxxx().
here i'm refer the item from
.then((data) => { var item = data[0]; var created = data[1];
as mentioned in https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html
size.ts
export const sizeModel = db.define<sizeInstance>("size", {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
title: {
type: DataTypes.STRING,
unique: "uk_size_title"
},
description: {
type: DataTypes.STRING,
},
isActiveRecord: {
type: DataTypes.BOOLEAN,
},
},
{
underscored: false
}
);
item.ts
export const itemModel = db.define(
"item",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
title: {
type: DataTypes.STRING,
validate: {
len: [3, 15]
}
},
description: {
type: DataTypes.STRING,
},
categoryId: {
type: DataTypes.INTEGER,
allowNull: false,
},
isActiveRecord: {
type: DataTypes.BOOLEAN,
defaultValue: true
},
},
{
indexes: [
{
unique: true,
fields: ["title", "categoryId"],
},
],
underscored: false
}
);
categoryModel.hasMany(itemModel, {
foreignKey: "categoryId",
});
//define the belongsTo association in the same file that you set the hasMany or the hasOne association.
itemModel.belongsTo(categoryModel, {
foreignKey: "categoryId",
});
Also I have itemsize.ts
export const itemsizeModel = db.define(
"itemsize",
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true,
allowNull: false,
},
isActiveRecord: {
type: DataTypes.BOOLEAN,
},
},
{
timestamps: false,
underscored: false
}
);
itemModel.belongsToMany(sizeModel, {
through: itemsizeModel,
foreignKey: 'item_itemId'
});
sizeModel.belongsToMany(itemModel, {
through: itemsizeModel,
foreignKey: 'size_sizeId'
});
itemcontroller.ts
await itemModel
.findOrCreate({
where: {
title: title,
categoryId: categoryId
},
defaults: {
title: title,
description: description,
categoryId: categoryId,
isActiveRecord: isActiveRecord,
},
})
.then((data) => {
var item = data[0];
var created = data[1];
if (created) {
Logger.info(
`Method: ${methodName}. Item '${title}' created successfully`
);
return res.status(200).json(item);
} else {
Logger.error(
`Method: ${methodName}. Item '${title}' already exists`
);
return res
.status(400)
.json({ message: `Item '${title}' already exists` });
}
})
.catch((err) => {
Logger.error(
`Method: ${methodName}. Failed to create item. Exception: ${err}`
);
return res.status(400).json(err);
});