假设您的数据模型如下:
/-----------------------\ /-----------------------\
| Patient | | Medication |
|-----------------------| |-----------------------|
| firstName | | startOn |
| lastName | | endOn |
|-----------------------| |-----------------------|
| medications | <<-\ | |
| | \->> | patients |
\-----------------------/ \-----------------------/
因此存在多对多的关系:患者服用多种药物,药物治疗患者很多。
如果有Patient
个对象,您如何获得最新Medication
的相关endOn
?
(假设:患者没有超过一种药物在同一天结束),即:
// patientZero is a patient with related medication records
Patient *patientZero = ...;
Medication *mostRecentMed = [patientZero mostRecentlyCompletedMedication];
如何实现mostRecentlyCompletedMedication
方法?
谢谢!
答案 0 :(得分:3)
这实际上不是核心数据问题,而是Cocoa集合问题。我会对medications
关联集进行排序。假设Patient =&gt; Medication to-many association被称为medications
:
Patient *myPatient;
NSSet *medications = [myPatient medications];
Medication *mostRecent = [medications sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"endOn" ascending:YES]]]
lastObject
];