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

标签 mysql node.js sequelize.js many-to-many sequelize-cli

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

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,
            }
        ]
    }).then(response => {
        console.log(response)
    }
    ).catch((ex) => {
        console.log("Error is here: ", 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 应指示作为第一个参数传递给 belongToMany 的模型:

House.belongsToMany(models.Users, {
          through: "Users_Has_House",
          foreignKey: "House_fk",
          otherKey: "Users_fk"
      });
Users.belongsToMany(models.House, {
                through: "Users_Has_House",
                foreignKey: "Users_fk",
                otherKey: "House_fk"
            });

关于mysql - 从多对多关系调用时,Sequelize 以复数形式搜索表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65980897/

相关文章:

node.js - Sequelize bulkcreate 抛出错误,语法错误位于或接近 ")"

php - 联系表7数据库扩展查询

php - 数据库中的简单 PHP 搜索不会显示结果

javascript - 使用 requirejs 和 typescript 的 Node 模块

node.js - 仅使用 PFX 的 Node JS https 服务器

node.js - 显示图库图像时无法读取每个 null 属性

node.js - 如何在不定义 Sequelize 模型的情况下使用 postgres 操作表

php - 查询和列出管理级别 - 连接两个表

php - 如何使用 codeigniter 连接多个列

node.js - 在基于 express.js 的应用程序中集中处理错误