Reputation: 1
How do I extract objects from a many-to-many relationship?
I am making an app which has the following entities in a many-to-many relationship.
Game <<--->> Team.
I would like to make labels which display the following objects: 'Game.id' and 'Team.name'.
When I fetch the Games Entity I can access the 'teams' NSSet but I can not extract the 'Team.name' object e.g 'Game.teams.name'.
I would like to return [Game 1, Team A, Team B]
relational diagram here for reference
Upvotes: 0
Views: 152
Reputation: 52088
You can't access it via 'Games.teams.name' since the collection doesn't have a name property so you have to loop over the set and extract the name from each individual team.
Of course if a game is a sports game it always has two team and then you might want to rethink your design and instead have two to-one relationships from game to team, like homeTeam and awayTeam. This might be easier to work with than a many-to-many relationship if you know there are always to teams in a game.
Example of accessing teams, assuming you have a game instance:
if let teams = game.teams as? Set<Team> {
for team in teams {
print(team.name)
}
}
Upvotes: 1