Reputation: 1013
Let's say I have two entities: Classroom and Student. The Classroom has a to-many relationship with student. Every student has a car (hascar is 1) or does not (hascar is 0)
I would like to create a couple of fetched properties on Classroom:
What is tripping me up is the syntax. How do I build a predicate that examines all of the students in a particular classroom?
Thank you!
Upvotes: 0
Views: 1454
Reputation: 64428
You don't need a fetch or a fetched property to examine all the students related to a particular classroom because the relationship finds the students automatically.
ClassRoom{
roomNumber:number
teacher:string
students<-->>Student.classroom
}
Student{
name:string
classroom<<-->ClassRoom.students.
}
Suppose you have a particular ClassRoom object, aClassRoom. The key aClassRoom.students returns a NSSet of all the related Student objects. All you need to do then is to use collection operators to get the information you want.
The number of students would be simple:
NSNumber *studentCount=[aClassRoom.students valueForKeyPath:@"@count"];
The number of students with cars:
NSPredicate *p=[NSPredicate predicateWithFormat:@"hasCar==1"];
NSNumber *withCars=[[aClassRoom.students filteredSetUsingPredicate:p] valueForKeyPath:@"@count"];
If you have a relationship, you don't ever need a fetch to find something about the objects in that relationship.
Upvotes: 3