Matt
Matt

Reputation: 435

CoreData fetch request - fetching all objects which have relationship

I have 3 entities:

Topic <--->> subTopic <--->> Certificate.

What I want is a list of all topics, where a certificate exists (with no duplicates). Based on my initial reading (mainly this question: CoreData performance: predicate on more to-many relationships) I worked out that the most efficient way (assuming it's possible) is to start at the certificate level, and derive the list of topics the list of certificates.

But that's as far as I got. How do I specify that while I want a list of topics back, the list I want will be based on all certificates? Is it possible to specify a predicate for the fetchrequest that can return a list of topics.

Is there a way of doing this without just manually following each certificate's relationships and just adding the topics found to an NSSet or something?

Thanks for any pointers (or equally - advise telling me to stop being silly, and here's the way I should be doing it!)

Upvotes: 2

Views: 1205

Answers (2)

Martin R
Martin R

Reputation: 540065

I cannot test this at the moment, but a fetch request on the Topic entity with this predicate should work:

[NSPredicate predicateWithFormat:@"SUBQUERY(subtopics, $s, ANY $s.certificates != NULL).@count > 0"]

Upvotes: 1

Wain
Wain

Reputation: 119041

Get all of the categories, however you want, no predicate required as you want all of them. Then get the topics like this (assuming sensible relationship names):

NSArray *topics = [[categories valueForKeyPath:@"@distinctUnionOfObjects.subtopic"] valueForKeyPath:@"@distinctUnionOfObjectstopic"];

Upvotes: 1

Related Questions