Reputation: 1
I have three Entities: Institution, Course, Student An Institution can have many Courses, a Course can have only one Institution (1 - many) A Course can have many Students, a Student can join many Courses (many - many).
Counting the Courses of an Institution is very simple, with its relation named "course":
int numberCourses = institution.course.count;
MY QUESTION:
How am I able to count the number of Students in an Institution? In Entity Course I have the relation "student" to Entity Student. How can I access from Institution thru Course to Student?
Note: A Student can be member in many courses and with that it's possible for him to be member of many Institutions.
Say it simple and analog to the code line above, I want this:
institution -> ALL courses -> student.count
Thank you for help!! C.
Upvotes: 0
Views: 406
Reputation: 540095
There are two different solutions. You can get the set of all students of the institution and count them:
NSSet *students = [institution valueForKeyPath:@"courses.students"];
NSUInteger numberOfStudents = [students count];
(I have used the plural form for to-many relationships which I find more intuitive.)
Or you build a fetch request for the students related to the institution:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Student"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY courses.institution == %@", institution];
[request setPredicate:predicate];
NSUInteger numberOfStudents = [context countForFetchRequest:request error:&error];
The second solution has the advantage that the Student objects and the intermediate Course objects are not loaded into memory. Counting the number of objects is done on the SQLite level.
Upvotes: 2