Relationship between tables with Sequelize

Asked

Viewed 911 times

1

I have two tables, one for Collaborator and one for Sector. A collaborator belongs to a sector and a sector contains several collaborators. I managed to create the tables, however, I don’t know how to make the relationship between the tables with Sequelize.

I saw some tutorials using belongsTo and hasToMany, but I get confused because I need to specify the field of the table that will be referenced not?

Here are the tables

Sector Table:

const Sequelize = require('sequelize');
const sequelize = require('../config/db');

const setor = sequelize.define('setor', {

    codigo: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },

    nome: {
        type: Sequelize.STRING,
        allowNull: false
    },

});

Contributor table:

const sequelize = require('../config/db');
const Sequelize = require('sequelize');


const Colaborador = sequelize.define('colaboradores', {

    codigo: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },

    nome: {
        type: Sequelize.STRING,
        allowNull: false
    },

    cargo: {
        type: Sequelize.STRING,
        allowNull: false
    },

    codigoSetor: {
        type: Sequelize.INTEGER,
        allowNull: false
    },

    email: {
        type: Sequelize.STRING,
        allowNull: false
    },

    senha:{
        type: Sequelize.STRING,
        allowNull: false
    },

    matricula: {
        type: Sequelize.STRING,
        allowNull: false
    }
})

1 answer

0

1 collaborator 'belongsTo' sector

1 sector 'hasMany' collaborator,

At Migration, you need to tell which field will be the foreign key! ex:

codigoSetor: {
    type: Sequelize.INTEGER,
    allowNull: false,
    references:{model: 'setor', key: 'codigo'}
    onUpdate:'CASCADE',
    onDelete:'CASCADE

}

and in the model you need to indicate the association.

ex:

static associate(models){
   this.'hasMany ou belongsto'(model.Setor,{foreignKey:'codigoSetor', as:'nome da assossiação'})
}

There is a video of Rocketseat explained well there! SQL on Node.Js with Sequelize

Browser other questions tagged

You are not signed in. Login or sign up in order to post.