views:

212

answers:

2

I have a relationship in a Core Data model that feels like it wants an association class. Specifically, I have a Person object, and a Location object. There is a many-to-many relation between these two classes, which has some properties, such as how many hours this person wishes to work at this location per week.

How do I model this using Core Data? A simple association between the two is part of the picture, but creating a new class which has the required properties as attributes, and then has a relationship to each of the other classes just doesn't feel quite right - for instance it allows for a relationship to not have the desired properties.

Am I missing something, or is this the best way to model this type of relationship?

A: 

From your question, it's not clear to me what constraints the model you propose can't handle. You can require that all of the properties of the association class be non-nil and that the relationship (to-one to a Person with a to-many return) and to-one (again with a to-many return) to a Location be non-nil. This requires that any association created has a Person and a Location and the desired association properties.

Barry Wark
If I remove the Association between the Person and the Location (without deleting either) then the... ah - now I see where you are coming from - there is no direct P-L relation. I'll see if this works.
Matthew Schinckel
+1  A: 

Core Data can model a to-many relationship. If two entities should have a many-to-many relationship, you would create a to-many relationship from Person to Location, and another to-many relationship from Location to Person. You would set those relationships as inverses of each other so that Core Data can keep the object graph consistent.

If you want a relationship to be required, you can set a minimum count for a to-many relationship.

Alex
This doesn't answer the question. How do you model an association class - to store attributes, eg the percentage of time at the location.
Matthew Schinckel
First, entities are not classes. There's a big difference. Second, if you're trying to model a location request, create a LocationRequest entity with to-one relationships with Person and Location. You're making this too complicated by trying to make Core Data behave like a database.
Alex