1
votes

Say I have 3 entities Grandparent, Parent, and Child.

Grandparent - Parent is a one to many relationship

Parent - Child is a many to one relationship

Child has an age attribute

My goal is to get all Child entities of Parent where Parent.grandparent is a certain Grandparent. In addition, I'd like to sort the fetched results by age. I know I can do this in multiple steps, but my question is: how can I accomplish this in a single fetch request?

Edit: Perhaps this diagram will be a bit clearer than the description above. enter image description here

2

2 Answers

0
votes

I've assumed variable and relationship names, change those to whatever you named them in your code and model.

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Child" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:@"parent.grandparent == %@", grandParentObject];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]];

This should work. I'm used to code completion and I didn't type this in Xcode, so the method names may be off a little, but you get the idea.

0
votes

I got lucky and found this answer NSPredicate acting strange in NSFetchedResultsController

The question was worded differently, which is why it took awhile for me to find it. Basically, the predicate I'm looking for is of the following format:

[NSPredicate predicateWithFormat:@"SUBQUERY(parent, $x, $x.grandparent == %@).@count != 0", grandParent];