theory
theory

Reputation: 9887

How do I craft a Core Data query of objects without an item in relationship?

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

Answers (1)

Daniel Eggert
Daniel Eggert

Reputation: 6715

Let me see if I get this right:

You have

  • Bucket with a name property
  • Item with a url property

and 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

Related Questions