【问题标题】:Sequelize: Wrong column names on junction table columnsSequelize:联结表列上的列名错误
【发布时间】:2022-02-18 12:05:36
【问题描述】:

我有一个 MySQL 数据库,其中所有内容都在 snake_case 中。我有两个具有多对多关系的模型(RoomBookingUser),以及一个手动定义的模型(称为MeetingGuest)作为它们的连接表(除其他外)。问题是,Sequelize 不断为这个联结模型生成带有PascalCase 列和表名的查询。

MeetingGuest 是使用 sequelize-cli 生成的,并经过调整变成这样:

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
}

它生成的查询是这样的:

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;

【问题讨论】:

  • 请添加关联定义
  • 我没有定义关联。如果我定义关联,它只会查询user 表。
  • 请显示为您提供该 SQL 查询的 Sequelize 查询。当然,UserMeetingGuest 之间至少有一个关联,以便能够在 Sequelize 查询中加入它们

标签: mysql node.js sequelize.js


【解决方案1】:

看来我必须将foreignKeyotherKey 添加到要关联的模型中。就我而言,它是RoomBooking不是连接表)。像这样:

const { Model } = require('sequelize')
const User = require('./User')
module.exports = (sequelize, DataTypes) => {
  class RoomBooking extends Model {
    static associate(models) {
      // define association here
      this.belongsTo(models.Room, {
        foreignKey: 'room_id',
      })
      this.belongsTo(models.User, {
        foreignKey: 'user_id',
        as: 'host',
      })
      this.belongsToMany(models.User, {
        through: models.MeetingGuest,
        foreignKey: 'room_booking_id',
        otherKey: 'user_id',
        as: 'guests',
      })
    }
  }
  RoomBooking.init(
    {
      user_id: {
        type: DataTypes.INTEGER,
        references: {
          model: 'User',
          key: 'id',
        },
      },
      room_id: DataTypes.INTEGER,
      // ...other fields
    },
    {
      sequelize,
      modelName: 'RoomBooking',
      tableName: 'room_bookings',
      createdAt: 'created_at',
      updatedAt: 'updated_at',
    },
  )
  return RoomBooking
}

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2021-02-07
    • 1970-01-01
    • 2016-01-14
    • 1970-01-01
    • 2016-04-11
    • 1970-01-01
    • 2015-04-17
    • 2018-12-17
    相关资源
    最近更新 更多