Search code examples
sqlnode.jspostgresqlsequelize.jsmany-to-many

How do i query a record from a through table and also get the data from the other two tables in sequelize?


i'm using Sequelize and this is my setup

// Event model
const Event = sequelize.define('event', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
}
/// Company model
const Company = sequelize.define('company', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  description: {
    type: DataTypes.STRING,
    allowNull: false,
  },
});
//CompanyEvent model
const CompanyEvent = sequelize.define('company_event', {
  companyId: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
  },
  eventId: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    allowNull: false,
  },
}, {
  tableName: 'company_events'
});

And then association declaration

Company.belongsToMany(Event, {
  through: 'company_events'
});
Event.belongsToMany(Company, {
  through: 'company_events'
});

What i'm trying to get is a query that can return this or something similar that i can get the data from both the company and event table.

{
  companyId: 1,
  eventId: 1,
  company: {
    id: 1,
    name: 'Some corp',
    description: 'Some description',
  },
  event: {
    id: 1,
    name: 'Some event',
  }
}

How can i achieve the above ? Thanks.


Solution

  • CompanyEvent.belongsTo(Company, {
      foreignKey: 'companyId',
      as: 'company'
    });
    CompanyEvent.belongsTo(Event, {
      foreignKey: 'eventId',
      as: 'event'
    });
    
    
    ...
    
    
    CompanyEvent.findAll({
        include: ['company', 'event']
    })