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);
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With