从多对多关系调用时,Sequelize 以复数形式搜索表

问题描述

我的“House”表是单数形式,我想使用多对多关系获取数据,但 sequelize 将“House”表视为“Houses”并且无法获取结果(即 []),这样调用

>
db.V1_DB.models.Users.findAll(
        include: [
            {
                model: db.V1_DB.models.House,}
        ]
    }).then(response => {
        console.log(response)
    }
    ).catch((ex) => {
        console.log("Error is here: ",ex)
    })

但成功获取了 House with Users 的结果,

db.V1_DB.models.House.findAll(
        include: [
            {
                model: db.V1_DB.models.Users,ex)
    })

我已经添加freezeTableName: true

我的模型是这样的。

'use strict';

const { Model } = require("sequelize");
module.exports = (sequelize,DataTypes) => {
  class House 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) {
      // define association here
      House.belongsToMany(models.Users,{
          through: "Users_Has_House",foreignKey: "Users_fk",});
    }
  }
  House.init({
    name: DataTypes.STRING,},{
    sequelize,modelName: 'House',freezeTableName: true,name: {
      singular: "House",plural: "House"
  }
  });
  return House;
};
'use strict';
const {
    Model
} = require('sequelize');
module.exports = (sequelize,DataTypes) => {
    class Users extends Model {
        //No Associations

        static associate(models) {
            // define association here

            Users.belongsToMany(models.House,{
                through: "Users_Has_House",foreignKey: "House_fk",});
        }
    };
    Users.init({
        Bio: DataTypes.TEXT,{
        sequelize,modelName: 'Users',});
    return Users;
};

解决方法

您需要更正关联,因为 foreignKey 选项应指示我们正在调用其 belongToMany 方法的模型,而 otherKey 应指示作为第一个参数传递给 { {1}}:

belongToMany