Jeg fik et fungerende svar. I dette eksempel har jeg en ordning, hvor en afdeling kan have mange stillinger. Stillingen vil omfatte afdelingen, og afdelingen vil inkludere dens stillinger.
models/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;
};
models/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;
};
controllere/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})
});
};