Associations with Node.JS / Sequelize

Asked

Viewed 648 times

1

Good evening dear friends,

I’m developing an API with Node.JS / Express / Sequelize and I need some help. As it is the first time that I use relational databases with Node, I don’t know exactly how to make a relationship between the tables Players and Teams. The logic is as follows:

  • A player belongs to only one team;
  • A team may have one or more players;

The models are as follows::

class Player extends Model {
    static init(sequelize) {
        super.init({
            name: type: DataTypes.STRING,
            nickname: type: DataTypes.STRING,
            position_id: DataTypes.INTEGER,
            team_id: DataTypes.INTEGER,
        }, {
            sequelize
        });
    }

    static associate(models) {
        // ???????????????????????????????????????????
    }
}

class Team extends Model {
    static init(sequelize) {
        super.init({
            name: type: DataTypes.STRING,
        }, {
            sequelize
        });
    }

    static associate(models) {
        // ???????????????????????????????????????????
    }
}

What is the right way to implement associations using Foreign Keys?

1 answer

3


You can create the relationship of the tables this way:

In the Team model:

static associate(models) {
this.belongsTo(models.Team, { foreignKey: 'team_id', as: 'team' }); };

In the Player model:

static associate(models) {
this.belongsTo(models.Player, { foreignKey: 'player_id', as: 'player' }); };

It is also necessary to make relationships in Migrations:

team_id: {
    type: Sequelize.INTEGER,
    references: { model: 'Team', key: 'id' },
    onUpdate: 'CASCADE',
    onDelete: 'SET NULL',
    allowNull: true,
  },

player_id: {
    type: Sequelize.INTEGER,
    references: { model: 'Player', key: 'id' },
    onUpdate: 'CASCADE',
    onDelete: 'SET NULL',
    allowNull: true,
  },
  • valeu brother! helped my ass out here

Browser other questions tagged

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