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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With