Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values from associated table with Sequelize.js

Tags:

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

I have a classical SQL JOIN problem - filled the match data and can't get the names of home and away teams that located in another table.

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 i understood from Docs after creating as: 'Home and as: 'Away i receive some getters and setters like Match.getHome but i'm confused. how can i used it

Match.find({where: {id: 1}}).success(function(match) {
    console.log(match);
});
like image 985
khex Avatar asked Nov 22 '13 22:11

khex


1 Answers

The problem lies in your association. You have only defined the assocation from team to match, but now you want to go the other way, from match to team. This means you have to do:

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

After that you can do

Match.find({where: {mid: 1}}).success(function(match) {
    match.getHome().success(function(home_team) {

    });
});

Or you can use eager loading:

Match.find({
    where: { mid: 1 }, 
    include: [
        { model: Team, as: 'Home'}
    ]
}).success(function(match) {
    // Here you can access the home team data in match.home
});

If you want both the home and away team at once:

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
});
like image 71
Jan Aagaard Meier Avatar answered Oct 17 '22 01:10

Jan Aagaard Meier