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

时间:2013-11-22 22:57:06

标签: sequelize.js

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之后从文档中了解到的那样,我收到了一些内容 像Match.getHome这样的傻瓜和二传手,但我很困惑。我怎么用呢

Match.find({where: {id: 1}}).success(function(match) {
    console.log(match);
});

1 个答案:

答案 0 :(得分:18)

问题在于你的关联。您只定义了团队之间的关联,但现在您想要从匹配到团队的另一种方式。这意味着你必须这样做:

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
});