0
votes

I have two Entities, Student and Course, where each has a to-many relationship to the other (i.e., a Student has 0 or more Courses, and a Course has 0 or more Students).

I need to obtain all Students who are enrolled in a Course. I also need to obtain all Courses in which a given Student is enrolled (by firstName).

An pseudo-predicate would be: all students who have a course whose name is equal to courseName.

So my question consists of two parts:

  1. What is a valid NSPredicate for obtaining all students with a certain course name?
  2. What is a valid NSPredicate for obtaining all courses where a student with a certain firstName is enrolled.

For your reference, here are my entities:

enter image description here

2
There will be a NSSet property in your NSManagedObject subclass, which returns students for a course object and courses for a student object.Akhilrajtr
if you are satisfied with any of the answers, please mark them correct. :)santhu
@santhu will do. need to try them out first. thanks!BigSauce

2 Answers

1
votes

1) Use this to filter an array of students that are in a specific course with courseName :

[NSPredicate predicateWithFormat:@"ANY courses.name like %@", courseName]

Alternatively, if you already have a course object (and name is unique in call course objects), you can simply get all of its students by accessing its students property, i.e.

course.students // returns an NSSet/NSOrderedSet based on your model setup

2) Use this to filter an array of courses that have a student with a certain firstName :

[NSPredicate predicateWithFormat:@"ANY students.firstName like %@", firstName]

Note: NSSet and NSOrderedSet have a method array to get an array of the objects.

See also the docs on NSPredicate under Using Predicates with Key-Paths.

1
votes

What is a valid NSPredicate for obtaining all students with a certain course name?

[NSPredicate predicateWithFormat:@"name= %@", courseName];

Use above predicate to fetch particular course while has name = courseName;Set that predicate on "Course" entity not "Student" entity.
AFter executing above fetch request, you will have array of courses having that courseName.

Course *course = [fetchedResults objectAtIndex:0];

Now to get all students in that course,

NSArray *students =[course.students allObjects];

now students is an array of "Student" entity objects.

Similarly , What is a valid NSPredicate for obtaining all courses where a student with a certain firstName is enrolled.

[NSPredicate predicateWithFormat:@"firstName = %@", name];

Use above predicate to fetch particular student who has name = firstName;Set that predicate on "Student" entity.
AFter executing above fetch request, you will have array of students having that firstName.

Student *student = [fetchedResults objectAtIndex:0];

Now to get all courses for that student,

NSArray *courses =[student.courses allObjects]; 

now courses is an array of "Course" entity objects.

Hope this helps.