问题
I'm just getting started with Core Data.
I have a Headache
entity and a Medication
entity. There is a many to many relationship between Headaches and Medications.
When you add a headache, you can choose multiple medications. I want to be able to specify quantities of those medications. I am more familiar with MySQL, where you would create a pivot table and include the quantity in the pivot table along with the headache_id and the medication_id so each instance could have a quantity.
Is there some way to create this kind of relationship in Core Data?
This is my Xcode data model.
回答1:
A many-to-many relationship can be modeled in Core Data. Core Data automatically creates an intermediate join table for you in the (SQLLite) persistent store.
What you can't do is add any attributes to that intermediate join table, since it is not a part of the object graph data model.
To represent the quantity, you could add a Dose entity to the object graph to model a many-one-many relationship between headaches, a quantity, and medications. This would represent the pivot you're thinking of, and the dose would function in the same way as an intermediate join table that Core Data would have created.
The downside is that there's no longer a medications relationship in the Headache
entity, or a headaches relationship in the Medication
entity.
If you really want to maintain that two-entity many-to-many relationship, you could add a dose attribute to the medication, but it would change the nature of your fetches. I.e., you would have to fetch all doses of a particular medication to find out which headaches were treated by that medication.
You should consider the specific fetches you'd be performing, and how you plan to traverse the object graph, then factor those requirements into the design of the model.
来源:https://stackoverflow.com/questions/35097263/core-data-attribute-on-relationship