Question

I have three entities.

I need to retrieve all the lectures that teach a certain student. So far the solution i was able to come up is

first to use a subquery to retrieve all the courses the student takes by

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(students, $student, $ student.name == 'student two').@count > 0"];

I execute the fetched request to obtain fetchedObjects.

Next i compare all the lecture objects with fetchedObjects. The lecture who conducts a course in fetchedObjects is the person who teaches the student in question.

Is there a much neater method of doing this without doing a comparison by hand ? I mean can i do it using predicates alone?

Was it helpful?

Solution

To fetch all lecturers that have a course with the given student, use the predicate

[NSPredicate predicateWithFormat:@"SUBQUERY(courses, $c, ANY $c.students.name == %@).@count > 0", studentName]

Remark: In your first example (fetch all courses for a student), you don't need a SUBQUERY:

[NSPredicate predicateWithFormat:@"ANY students.name == %@", studentName]

OTHER TIPS

Do you want to retrieve "Course" entity or "Lecturer" entities ?

for Course you could try this predicate

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"students.name = %@",NAME];

now you have Course entities and you can get Lecturers too,

for Lecturers you could try

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY courses.@unionOfArrays.students.name = %@",NAME];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top