Ik heb een werkend antwoord gekregen. In dit voorbeeld heb ik een schema waarbij een afdeling veel functies kan hebben. De positie omvat de afdeling en de afdeling omvat zijn posities.
modellen/Department.js
module.exports = (sequelize, DataTypes) =>
{
const Sequelize = require('sequelize');
const Department = sequelize.define('Department',
{
...
}
Department.associate = function(models) {
Department.hasMany(models.Position, {
foreignKey: 'department_id',
as: 'positions'
});
};
return Department;
};
modellen/Position.js
module.exports = (sequelize, DataTypes) =>
{
const Sequelize = require('sequelize');
const Position = sequelize.define('Position',
{
...
}
Position.associate = function(models) {
Position.belongsTo(models.Department, {
foreignKey: 'department_id',
as: 'department',
onDelete: 'CASCADE'
});
};
return Position;
};
controllers/departmentController.js
exports.all = async function(req, res)
{
return Department
.findAll({include: [ 'positions' ]})
.then((data) => {
if (!data) { return res.status(400).json({status: 400,message: 'Registro não encontrado', data: data }); }
return res.status(200).json(data);
})
.catch((error) => {
return res.status(400).json({message: 'Falha no banco de dados.', data: error})
});
};
controllers/positionController.js
exports.all = async function(req, res)
{
return Position
.findAll({include: [ 'department' ]})
.then((data) => {
if (!data) { return res.status(400).json({status: 400,message: 'Registro não encontrado', data: data }); }
return res.status(200).json(data);
})
.catch((error) => {
console.log(error);
return res.status(400).json({message: 'Falha no banco de dados.', data: error})
});
};