Search code examples
iosswiftcore-data

CoreData and intermediates


I am a little confused as to how to model this in CoreData. It's fairly simple concept — I want to be able to track how long a player has played in a certain game. So, I have the following objects (simplified for brevity):

Player
 - name
 - currentGamePlayedTime
 (1:1 relationship to Team)

Team
 - name
 (1:1 relationship with Player)
 (1:Many relationship with Game

 Game
  - date
  (Many:1 relationship with Team)

I want to be able to look back at a player's playing time in a certain game, or see the whole team's playing time in a game. But I'm unsure how to model that. Using an SQL approach I'd have an intermediate table (shown below), and have 15 entries or so, one for each player who played in the game and the corresponding time they played.

GameRecord
 - GameID
 - PlayerID
 - TimePlayed

My app is able to workout how much a player has played in the current game and store it on the Player object currently, but I don't know the long-term solution to saving that playing time to a corresponding Game object — whether that's directly on the object or via an intermediate.

I've seen that some people do use intermediates. But I've also read that using SQL practices isn't the right way to think about the object graph. So, just wanted an idea of how something like this should be modeled.


Solution

  • Using intermediate entities to model many-many relationships is perfectly legitimate. Indeed, it is necessary in situations such as yours where you want to store information about the relationship itself.

    There is an example of this in the Core Data Programming Guide, in the section entitled "Modeling a relationship based on its semantics" (whatever that means). Their example is a reflexive relationship, but the argument applies to any many-many relationship.