简体   繁体   中英

CoreData: How to model circular many-to-many relationships

Been trying to understand how to model a circular core-data many-to-many relationship in Xcode 4.2. In SQL I would be using mapping tables and customize my SQL expressions to give me the right data, but in Core data I can't seem to understand how to get his to work properly. I have 3 entities which are all related to each other:

  • Department
  • Role
  • Person

My links are:

  • Department can have multiple Roles
  • Department can have multiple Persons
  • A role can be present at many departments
  • A role can have many persons assigned to it
  • A person can belong to multiple departments
  • A person can be part of many roles

What is the best way to model this using Core data and which entites, with which relationships between them would be most adequate? Would you use mapping tables between these 3, or just assign the correct relationships?

Any help would be highly appreciated as I can't seem to figure this out....

EDIT: Thank you very much for the fast feedback. Unfortunately I can't upload my data model as I am new to this site and not allowed to post any images.

To read the data I am currently only using a Predicate like this:

predicate = [NSPredicate predicateWithFormat:@"personPartOfRoles == %@", myRole];

What I can't seem to figure out is how to maintain this object graph to add or remove persons from roles. I have assumed I need to load up the entire graph in memory and somehow find only the correct entities to map in.

Just assign the correct relationships in your entities.

If you are going to use Core Data it is important to ignore the fact that you are storing in SQLite. The storage is simply a behind the scenes implementation detail (as coredata is capable of storing in XML or in memory) that you can forget about.

Department <<--->> Role (roles to departments)
Department <<--->> Person (departments to people)
Role <<-->> Person (roles to people)

Make each relationship have an inverse.

Remember that Core Data is an object graph that can persist to a database. Treat it like an object graph.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM