核心数据:从两个实体获取结果,结果包含两个实体中的信息

时间:2013-05-23 13:08:50

标签: ios core-data

有两个实体:

enter image description here

我想制作课程表。

第一个实体是Course,第二个实体是TimeAndPlace。在大学里,有一些课程和一门课程可能有不同的时间或地点。现在我想在每个工作日中获取Course s及其关联的TimeAndPlace s。但是有一些限制:如果当前一周是在开始周和上周之间的期限,则需要课程;在这些课程中,选择工作日等于某个工作日的课程。最后,我想了解课程及其相关的时间和地点。

我对Core Data不太熟悉,你能帮助我吗?

被修改: 就像SQL:

SELECT Course.courseName, TimeAndPlace.courseLocation, TimeAndPlace.courseOrder
FROM Course, TimeAndPlace
WHERE Course.startWeekTheCourseInTheTerm <= currentWeek AND Course.lastWeekTheCourseInTheTerm >= currentWeek AND timeAndPlaces.weekday == currentweekday;

效果图:

enter image description here

1 个答案:

答案 0 :(得分:1)

也许是这样的?使用1:n关系并不复杂,n:m:P

会更有趣
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Course" inManagedObjectContext:context]];

NSPredicate* = [NSPredicate predicateWithFormat:@"startWeekTheCourseInTheTerm <= %d AND lastWeekTheCourseInTheTerm >= %d AND timeAndPlaces.weekday == %d", currentWeek, currentWeek, weekday];
[fetchRequest setPredicate:predicate];

或者如果你需要完整的一周(例如在tableView中显示)

NSPredicate* = [NSPredicate predicateWithFormat:@"startWeekTheCourseInTheTerm <= %d AND lastWeekTheCourseInTheTerm >= %d", currentWeek, currentWeek];
[fetchRequest setPredicate:predicate];

[fetchRequest setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"timeAndPlaces.weekday" ascending:YES]]];

按工作日和courseOrder排序:
(所以你有

- &GT;周一
- &GT; 1
- &GT; 2
- &GT; 3
- &GT;周二
- &GT; 1
...

[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:[[NSSortDescriptor alloc] initWithKey:@"timeAndPlaces.weekday" ascending:YES], [[NSSortDescriptor alloc] initWithKey:@"timeAndPlaces.courseOrder" ascending:YES], nil]];

最后一步:抓取

NSError* err = nil;
list = [NSMutableArray arrayWithArray:[context executeFetchRequest:fetchRequest error:&err]];
[fetchRequest release];