gpt4 book ai didi

sequelize.js - 使用 Sequelize.js 从关联表中获取值

转载 作者:行者123 更新时间:2023-12-04 00:44:32 26 4
gpt4 key购买 nike

team table               match table
=========== ================================
tid= name mid= date =home_team=away_team
============= ================================
01 = denver 01 =10.11.13 = 01 = 04
02 = minesota 02 =11.11.13 = 02 = 03
03 = orlando 03 =11.11.13 = 04 = 02
04 = portland 04 =12.11.13 = 03 = 01

我有一个经典的 SQL JOIN 问题 - 填充了比赛数据,但无法获得位于另一个表中的主客队名称。
var Team = sequelize.define('Team', { ... });
var Match = sequelize.define('Match',{ .. });

Team.hasOne(Match, {foreignKey: 'home_team', as: 'Home'})
Team.hasOne(Match, {foreignKey: 'away_team', as: 'Away'});

正如我在创建后从文档中了解到的 as: 'Homeas: 'Away我收到一些
getter 和 setter,如 Match.getHome但我很困惑。我该如何使用它
Match.find({where: {id: 1}}).success(function(match) {
console.log(match);
});

最佳答案

问题在于你的协会。您只定义了从一个团队到另一个匹配的关联,但现在您想要走另一条路,从一个匹配到另一个团队。这意味着您必须执行以下操作:

Match.belongsTo(Team, {foreignKey: 'home_team', as: 'Home'});
Match.belongsTo(Team, {foreignKey: 'away_team', as: 'Away'});

之后你可以做
Match.find({where: {mid: 1}}).success(function(match) {
match.getHome().success(function(home_team) {

});
});

或者你可以使用预先加载:
Match.find({
where: { mid: 1 },
include: [
{ model: Team, as: 'Home'}
]
}).success(function(match) {
// Here you can access the home team data in match.home
});

如果您同时想要主客队:
Match.find({
where: { mid: 1 },
include: [
{ model: Team, as: 'Home'}
{ model: Team, as: 'Away'}
]
}).success(function(match) {
// Here you can access the home team data in match.home and away team in match.away
});

关于sequelize.js - 使用 Sequelize.js 从关联表中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156045/

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