Reputation: 10530
I need to make a fetch request, and I can't quite figure out the NSPredicate I need for the request. Here's the scenario:
I have a List
entity, and the list
object has a to-many relationship to a set of Request
objects. Each Request
object has a to-many relationship to a set of Tags
objects.
I need perform a fetch request on the Tags
entity, but I can't figure the NSPredicate
for the call. I would like to only pull out the tags
that are in all the tags of all the requests of a specific list.
Here's what I've tried:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"tag in ANY list.requests.tags"];
But I know this isn't right. I'm not able to specify my list, also list.requests
returns an NSSet
, and I can't just do .tags
on a set. I'm pretty stuck.
I've attached a pic of relationships in case that helps:
Upvotes: 2
Views: 922
Reputation: 57060
Create a sub-query.
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(requests, $request, $request.list = %@).@count > 0", list];
This counts the requests which have a specified list; if the count is more than one, the tag is taken.
You can also do:
[list.requests valueForKeyPath:@"tags.@distinctUnionOfSets"]
This uses key-value coding to retrieve all the tags that belong to all the requests and unifies them into a set. This method is less efficient than the former.
Upvotes: 2