gpt4 book ai didi

node.js - Sequelize 自引用不能进行连接

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

我正在尝试使用不同球队的比赛制作多对多表格并且它有效,但是当我尝试加入时出现此错误:

Unhandled rejection Error: team is not associated to match!

这是我的代码:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('cricket', 'root', '');


var Team = sequelize.define('team', {
name: Sequelize.STRING,
});

var Match = sequelize.define('match', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
scoreHome: Sequelize.INTEGER,
scoreAway: Sequelize.INTEGER,
});


Team.belongsToMany(Team, {as: 'Home', through: Match, foreignKey: 'homeTeamId'});
Team.belongsToMany(Team, {as: 'Away', through: Match, foreignKey: 'awayTeamId'});

sequelize.sync().then(function () {
Match.findAll({
include: [ Team ]
}).then(function (matches) {
console.log(matches)
});
});

最佳答案

您还需要为 Match 提供反向关系。

在您当前的设置中,Team 与 Team 相关联,而不是与 Match 相关联。 Match 模型是您的直通模型。

例如,匹配的有效关联是:

var HomeTeam = Match.belongsTo( Team, { as: 'HomeTeam', foreignKey: 'homeTeamId' });
var AwayTeam = Match.belongsTo( Team, { as: 'AwayTeam', foreignKey: 'awayTeamId' })

sequelize.sync().then(function () {
Match.findAll({
include: [ HomeTeam, AwayTeam ]
}).then(function (matches) {
console.log(matches)
});
});

// Makes the following query

// SELECT `match`.`id`, `match`.`scoreHome`, `match`.`scoreAway`, `match`.`createdAt`, `match`.`updatedAt`, `match`.`homeTeamId`, `match`.`awayTeamId`, `HomeTeam`.`id`
// AS `HomeTeam.id`, `HomeTeam`.`name` AS `HomeTeam.name`, `HomeTeam`.`createdAt`
// AS `HomeTeam.createdAt`, `HomeTeam`.`updatedAt` AS `HomeTeam.updatedAt`, `AwayTeam`.`id` AS `AwayTeam.id`, `AwayTeam`.`name` AS `AwayTeam.name`, `AwayTeam`.`createdAt` AS `AwayTeam.createdAt`, `AwayTeam`.`updatedAt` AS `AwayTeam.updatedAt` FROM `matches` AS `match` LEFT OUTER JOIN `teams` AS `HomeTeam` ON `match`.`homeTeamId` = `HomeTeam`.`id` LEFT OUTER JOIN `teams` AS `AwayTeam` ON `match`.`awayTeamId` = `AwayTeam`.`id`

关于node.js - Sequelize 自引用不能进行连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40691535/

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