Shawn Throop
Shawn Throop

Reputation: 1291

Is a self referential one-to-many Core Data relationship possible?

I’m learning to use Core Data and I have some ideas for modeling data. As someone trying to learn German, I’m making a log book of phrases and some context around them like the text’s language, a note, and possible translations.

First Idea

Here’s a very simplified model:

class Phrase: NSManagedObject {
  @NSManaged var text: String
  @NSManaged var language: String
  @NSManaged var translations: Set<Phrase>
  @NSManaged var note: String?
}

The translations property would be a one-to-many relationship. Is this even possible given how Core Data stores data?

Second Idea

In my research it sounds like I might need an intermediate object to facilitate a join table. Something more like this:

class Phrase: NSManagedObject {
  @NSManaged var text: String
  @NSManaged var language: String
  @NSManaged var translations: Set<Translation> // one-to-many: Translation.input
  @NSManaged var note: String?
}

class Translation: NSManagedObject {
  @NSManaged var input: Phrase // one-to-many: Phrase.translations
  @NSManaged var text: String
  @NSManaged var language: String
  @NSManaged var note: String?
}

Conclusion

I feel like I might be thinking of the problem incorrectly. Is there a better model for this structure?

Upvotes: 0

Views: 209

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70966

Either of those will work but it's important to be aware of how Core Data differs from a relational database. In both cases Core Data will complain that there's no inverse relationship. It expects to have a property for the relationship on both ends. In the first case it will expect a second relationship that you might call translatedFrom or something. You don't ever need to use that relationship, but it's good to have it for Core Data's internal use.

Aside from that you can go with either approach. The second has the possible advantage that you can add notes or other data specifically about the translation, separately from each phrase. If you don't need that though, don't bother with a second entity.

Upvotes: 1

Related Questions