views:

121

answers:

2

Hi there,

I'm fairly new to Objective C and Core Data and have a problem designing a case where players team up one-on-one and have multiple matches that end up with a specific result.

With MySQL, I would have a Player table (player primary key, name) and a match table (player A foreign key, player B foreign key, result).

Now how do I do this with Core Data? I can easily tie a player entity to a match entity using a relationship. But how do I model the inverse direction for the second player ref. in the match entity?

Player
Name: Attribute
Match: Relationship Match

Match
Result: Attribute PlayerA: Relationship to Player (<- Inverse to Player.Match)
PlayerB: Relationship to Player (<- Inverse to ????)

Would be great if someone could give me an idea on this!

Thanks, Stevie.

A: 

If your match has a specific home player and away player, then you would use:

player.homeMatches <---->> match.homePlayer
player.awayMatches <---->> match.awayPlayer

You may still have the:

player.matches

if you need to search by all matches and you don't want to AND your search fields together. Or you can provide a method/readonly-property "allMatches":

- (NSSet *)allMatches
{
    return [[NSMutableSet setWithSet:self.homeMatches] unionSet:self.awayMatches];
}

to give the value at runtime. Of course, you can't search by this "allMatches" property using a fetch predicate but you can sort and access at runtime.

Matt Gallagher
A: 

Matt, thanks for the answer. This sounds reasonable when I can distinguish between matches a player has home and away and I might get away with it in this particular case! ;-)

But what if the match does not have a specific home or away player. If it is simply matches the players have?

Stevie
I think all you're looking for is a many-to-many relationship. i.e.:player.matches <<------->> match.playersThen you can easily add your players to the match:[match addPlayersObject:player1];[match addPlayersObject:player2];
Matt Gallagher
@Matt that would also add the advantage of not allowing a Player to be both the homePlayer and the awayPlayer. However, if you want to keep the distinction of home vs away, you'd need to have another way to express that.
Dave DeLong