我的“房子”表是单数形式,我想使用多对多关系获取数据,但 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/