E
E
Evgeny Petrov2020-04-25 12:28:51
ORM
Evgeny Petrov, 2020-04-25 12:28:51

What are associations for in Sequelize?

Hello!

Can someone please explain what associations are needed in Sequelize like hasMany, belongsTo etc.? The documentation says that to create a foreign key in the model, but why do I need them if I set the foreign key when creating the table in the migration files, for example:

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Orders', {
      name: {
        type: Sequelize.STRING(50)
      },
      category: {
        type: Sequelize.INTEGER(5),
        references: {
          model: "Categories",
          key: "id"
        },
        onUpdate: "CASCADE",
        onDelete: "RESTRICT"
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Orders');
  }
};

In the code above, I have already set the foreign key at the table creation stage, then why should I use these associations? Thank you in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2020-04-25
@notiv-nt

For model methods
https://sequelize.org/master/manual/assocs.html#sp...
and include in find

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question