我有2个模型,通过另一个模型具有多对多关联。默认情况下,众所周知,Sequelize为这两个模型创建实例方法(https://sequelize.org/master/manual/assocs.html#special-methods-mixins-added-to-instances)。
我的问题是fooInstance.getBars()方法和fooInstance.countBars()都返回错误的记录数。
[数据库是使用后续迁移文件设置的。
以下是3种型号。
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define(
"User",
{
firstName: DataTypes.STRING
},
{}
);
User.associate = function(models) {
// associations can be defined here
User.belongsToMany(models.Week, {
through: models.Roster,
foreignKey: {
name: "weekId"
}
});
};
return User;
};
"use strict";
module.exports = (sequelize, DataTypes) => {
const Week = sequelize.define(
"Week",
{
date: {
type: DataTypes.DATE,
allowNull: false,
unique: true
}
},
{}
);
Week.associate = function(models) {
// associations can be defined here
Week.belongsToMany(models.User, {
through: models.Roster,
foreignKey: {
name: "userId",
allowNull: true
}
});
};
return Week;
};
"use strict";
module.exports = (sequelize, DataTypes) => {
const Roster = sequelize.define(
"Roster",
{
weekId: {
type: DataTypes.INTEGER,
allowNull: false,
unique: false
},
userId: {
type: DataTypes.INTEGER,
allowNull: true,
unique: false
}
},
{}
);
Roster.associate = function(models) {
// associations can be defined here
};
return Roster;
};
在测试方法之前,我在几周内创建了1条记录,在用户中创建了5条记录,然后使用5名Roster.create()在名册中创建了5个关联。
[当我像await Week.getUsers()
这样在路由文件中进行查询时,它没有在数组中返回5个用户,而是在数组中返回了1个用户。同样,await Week.countUsers()
代码返回1而不是5。
请帮助!
如果错过任何重要信息,请告诉我。
谢谢!
我有2个模型,通过另一个模型具有多对多关联。默认情况下,众所周知,Sequelize会为两个模型创建实例方法(https://sequelize.org/master/manual/assocs ....
[像docs说: