gpt4 book ai didi

sequelize.js - SequelizeEagerLoadingError 和关联

转载 作者:行者123 更新时间:2023-12-03 22:39:57 32 4
gpt4 key购买 nike

我有两个相互关联的模型,如下所示:

TeamFormationMinutes.associate = (models) => {
models.TeamFormationMinutes.belongsTo(models.Game);
}

Game.associate = (models) => {
models.Game.hasMany(models.TeamFormationMinutes);
};

我想创建一个查询来模拟这个原始查询:
select distinct(T.game_id) from TeamFormationMinutes T inner join Games G on T.game_id = G.id where G.competition_id=112 and G.season=2016;

这是我所做的:
const leagueSeasonMatches = await models.TeamFormationMinutes
.findAll({
include: [{
model: models.Game,
where: {competition_id: 112, season: 2016}
}],
plain: true,
distinct: 'game_id'
});

但是当我运行它时,我收到 SequelizeEagerLoadingError: Game is not associated to TeamFormationMinutes! 错误。就我而言,我定义了这两个模型之间的关联。我在这里缺少什么?

模型如下:
'use strict';

module.exports = (sequelize, DataTypes) => {
const TeamFormationMinutes = sequelize.define('TeamFormationMinutes', {
team_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
team_formation_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
game_id: {
type: DataTypes.INTEGER,
primaryKey: true
},
duration: {
type: DataTypes.INTEGER,
primaryKey: true
}
}, {
underscored: true
});

TeamFormationMinutes.associate = (models) => {
models.TeamFormationMinutes.belongsTo(models.Game);
models.TeamFormationMinutes.belongsTo(models.Team);
models.TeamFormationMinutes.belongsTo(models.TeamFormation);
};

return TeamFormationMinutes;
};

最佳答案

如果您反转 findAll ,它将像 Game 具有 hasMany 关联一样工作

const result = await models.Game
.findAll({
where: {competition_id: 112, season: 2016}
include: [{
model: models.TeamFormationMinutes,
}],
plain: true,
distinct: 'game_id'
});

您是否将 foreign-key constraints 定义为数据库架构的一部分。应该看起来像这样吗?

enter image description here

关于sequelize.js - SequelizeEagerLoadingError 和关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689151/

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