Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: Wrong column names on junction table columns

I have a MySQL database where everything is in snake_case. I have two models with many-to-many relationship (RoomBooking and User), and one manually-defined model (called MeetingGuest) that acts as their junction table (among other things). The problem is, Sequelize keeps generating queries with PascalCase column and table names for this junction model.

MeetingGuest is generated using sequelize-cli, and tweaked to become like so:

const { Model } = require('sequelize')
module.exports = (sequelize, DataTypes) => {
  class MeetingGuest extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {

    }
  }
  MeetingGuest.init(
    {
      room_booking_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'RoomBooking',
          key: 'id',
        },
      },
      user_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'User',
          key: 'id',
        },
      },
      status: DataTypes.STRING,
      check_in: DataTypes.BOOLEAN,
    },
    {
      sequelize,
      modelName: 'MeetingGuest',
      tableName: 'meeting_guests',
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    },
  )
  return MeetingGuest
}

The query it generates is like this:

SELECT
MeetingGuest.RoomBookingId,   -- `room_booking_id` is never aliased into RoomBookingId
-- Other selected columns...
FROM `users` AS `User`
INNER JOIN `meeting_guests` AS `MeetingGuest`
ON `User`.`id` = `MeetingGuest`.`UserId` AND `MeetingGuest`.`RoomBookingId` = 1;

like image 492
starleaf1 Avatar asked May 26 '26 04:05

starleaf1


1 Answers

Defining the foreign keys explicitly is the key.

I went from

modelA.belongsToMany(modelB,
  { through: associativeTable }
);
modelB.belongsToMany(modelA,
  { through: associativeTable }
);

to

modelA.belongsToMany(modelB,
  { through: associativeTable, foreignKey: 'modelA_id' }
);
modelB.belongsToMany(modelA,
  { through: associativeTable, foreignKey: 'modelB_id' }
);

And now everything is peachy

like image 87
Félix Paradis Avatar answered May 27 '26 17:05

Félix Paradis