gpt4 book ai didi

associations - belongsTo - hasMany - 从 belongsTo 获取实例 - sequelize

转载 作者:行者123 更新时间:2023-12-03 22:20:27 24 4
gpt4 key购买 nike

如果我有以下型号:

module.exports = function (sequelize, DataTypes) {
var WorkingCalendar = sequelize.define('WorkingCalendar', {
date: DataTypes.DATEONLY,
isWorking: DataTypes.BOOLEAN,
}, {
indexes: [{
unique: true,
fields: ['PeriodId', 'date']
}]
}, {
classMethods: {
associate: function (models) {
WorkingCalendar.belongsTo(models.Period);
}
}
});
return WorkingCalendar;
};

module.exports = function(sequelize, DataTypes) {
var Period = sequelize.define('Period', {
name: DataTypes.STRING,
numberOfPeriods: DataTypes.INTEGER
}, {
classMethods: {
associate: function(models) {
Period.hasMany(models.WorkingCalendar);
}
}
});
return Period;
};

然后尝试获取 Period通过 WorkingCalendar如下:
return models.WorkingCalendar
.findAll({
attributes: [
'PeriodId',
'date'
],
include: [
{ model: models.Period }
],
group: ['date', 'PeriodId']
});

我收到以下错误: 未处理的拒绝错误:期间与 WorkingCalendar 无关!

然而,它确实反过来起作用。

我的问题:
为什么我不能得到 Period通过 WorkingCalendar ?我该怎么做才能确保我能做到?

我已经试过把 foreignKey关联上的属性以及 as具有约束力,但遗憾的是无济于事。非常欢迎任何帮助!

最佳答案

所以终于找到了。indexes应该与 classMethods 在同一个对象中

错误

module.exports = function (sequelize, DataTypes) {
var WorkingCalendar = sequelize.define('WorkingCalendar', {
date: DataTypes.DATEONLY,
isWorking: DataTypes.BOOLEAN,
}, {
indexes: [{
unique: true,
fields: ['PeriodId', 'date']
}]
}, {
classMethods: {
associate: function (models) {
WorkingCalendar.belongsTo(models.Period);
}
}
});
return WorkingCalendar;
};


module.exports = function (sequelize, DataTypes) {
var WorkingCalendar = sequelize.define('WorkingCalendar', {
date: DataTypes.DATEONLY,
isWorking: DataTypes.BOOLEAN,
}, {
indexes: [{
unique: true,
fields: ['PeriodId', 'date']
}],
classMethods: {
associate: function (models) {
WorkingCalendar.belongsTo(models.Period);
}
}
});
return WorkingCalendar;
};

关于associations - belongsTo - hasMany - 从 belongsTo 获取实例 - sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38223541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com