Reputation: 9887
Say I have a Core Data entity called "Bucket". A Bucket has a name and a many-to-one relationship, named "items", to an entity named "Item", which have an attribute, "url". Business rule requires that an item with a given URL can be in a bucket only once. (Aside: Man I would love proper constraints in Core Data!) Here's my question: How can I fetch Buckets that do not contain an Item with a given URL?
IOW, how might I do the equivalent of this SQL in core data?
SELECT name FROM buckets
WHERE bucket_id NOT IN (
SELECT bucket_id FROM items WHERE url = ?
);
Is that possible using predicates for core data fetch requests?
Upvotes: 2
Views: 163
Reputation: 6715
Let me see if I get this right:
You have
Bucket
with a name
propertyItem
with a url
propertyand a relationship like this
Bucket
<--->> Item
i.e. a bucket can have multiple items, but each item is only in one bucket.
Now, what you need is a Subquery Expression:
(SUBQUERY(items, $x, $x.url == %@).@count == 0)
i.e.
NSString *urlAsString; // Assume we have this
NSPredicate *p = [NSPredicate predicateWithFormat:@"(SUBQUERY(items, $x, $x.url == %@).@count == 0)", urlAsString];
And you'll want an index on url
for Item
for performance reasons.
Upvotes: 2