Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data Relationships

Supposing you had a data model that looks like:

/-----------------------\          /-----------------------\
| Patient               |          | Medication            |
|-----------------------|          |-----------------------|
| firstName             |          | startOn               |
| lastName              |          | endOn                 |
|-----------------------|          |-----------------------|
| medications           | <<-\     |                       |
|                       |     \->> | patients              |
\-----------------------/          \-----------------------/

So there is a many-to-many relationship: patients have many medications and a medication has many patients.

Given a Patient object, how would you get the related Medication with the most recent endOn? (assumption: a patient does not have more than one medication that ends on the same date) i.e.:

// patientZero is a patient with related medication records
Patient *patientZero = ...;
Medication *mostRecentMed = [patientZero mostRecentlyCompletedMedication];

How would one implement the mostRecentlyCompletedMedication method?

Thanks!

like image 705
Bill Shiff Avatar asked Feb 03 '26 23:02

Bill Shiff


1 Answers

This is actually not a Core Data question, but a Cocoa collections question. I would sort the medications association set. Assuming the Patient=>Medication to-many association is called medications:

Patient *myPatient;

NSSet *medications = [myPatient medications];
Medication *mostRecent = [medications sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"endOn" ascending:YES]]]
                           lastObject
                          ];
like image 107
Barry Wark Avatar answered Feb 05 '26 14:02

Barry Wark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!