I have two models:
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Company extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
Company.hasOne(models.CompanyModules, {
foreignKey: "company_uuid",
sourceKey: 'uuid',
hooks: true
})
}
};
Company.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
uuid: {
type: DataTypes.STRING,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
//.... more fields
}, {
sequelize,
modelName: 'Company',
paranoid: true,
hooks: {
afterDestroy: (instance) => {
instance.getCompanyModules().then(companyModule => companyModule.destroy())
}
}
});
return Company;
};
And the other:
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class CompanyModules extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
CompanyModules.belongsTo(models.Company, {
foreignKey: 'company_uuid',
targetKey: 'uuid',
onDelete: 'CASCADE'
});
}
};
CompanyModules.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
uuid: {
type: DataTypes.STRING,
defaultValue: DataTypes.UUIDV4
},
///... more fields
}, {
sequelize,
modelName: 'CompanyModules',
paranoid: true
});
return CompanyModules;
};
I have the following delete code:
await Company.destroy({
where: { id: req.params.id },
individualHooks: true
})
res.status(200).send();
And the idea is that it "Deletes" (actually updating the deletedOn field) on both models. However I am getting an error on the instance.getCompanyModules(). It says that the function doesn't exist, but that's how I read it's supposed to be done. Am I missing something here?