3

I can't understand what's wrong with my predication. I have the next database scheme:

DataItem(color_ids) <->> (dataItem)Color

Where Color contains colorID(int).

I tried to get

all DataItems that contain colorID == 5.

I have used the next predicate:

SUBQUERY(color_ids, $sub, $sub.colorID==5).@count > 0

Thanks for your help.

TechZen
  • 64,370
  • 15
  • 118
  • 145
  • 7
    Your clearly trying to use Core Data like SQL. Don't do that. Core Data is not SQL. Entities are not tables. Objects are not rows. Attributes are not columns. Relationships are not joins. Core Data is an object graph management system that may or may not persist the object graph and may or may not use SQL far behind the scenes to do so. Trying to think of Core Data in SQL terms will cause you to completely misunderstand Core Data and result in much grief and wasted time. – TechZen Jul 31 '11 at 16:10
  • 1
    So what are we gonna do then. everyone"s first experience is sql (mostly mysql), when I read that coreData is sqlite based, I said ok I already did deal whit this. But you are saying that we should not do that (I can say you are right after some grief I had already) . So where Can I go to learn coreData the right way? – Siempay Dec 11 '18 at 17:31

1 Answers1

9

You don't need SUBQUERY for this. In fact, you almost never need SUBQUERY; it is extremely rare to find a situation where it is the correct thing to use.

You can do this instead:

[NSPredicate predicateWithFormat:@"ANY color_ids.colorID == 5"];
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • This works great. How would you go one level deeper? Say we have A <-->> B <-->> C. We have multiple A entities and C entities have an attribute called label. How can I find all A entities that contain C entities with label == @"1234"? – zumzum Aug 16 '12 at 20:51
  • 4
    @zumzum For that you probably would need a `SUBQUERY`, and it'd be something like: `SUBQUERY(aToBs, $b, ANY $b.bToCs.label = '1234').@count > 0` – Dave DeLong Aug 16 '12 at 20:57
  • Thanks. I'll work on this and will let you know how it goes as soon as I'm done. Do SUBQUERIES work on iOS? – zumzum Aug 17 '12 at 03:10
  • I did exactly what Dave suggested above and it worked great. Thanks Dave! Here's the exact predicate in case somebody wants the exact code I am using in case it helps. NSPredicate * sp = [NSPredicate predicateWithFormat:@"SUBQUERY(catalogItemClasses, $b, ANY $b.catalogItems.label contains[cd] %@).@count > 0", searchText]; – zumzum Aug 17 '12 at 04:39
  • 1
    You can form it as an answer to your question and acept it, that would ve right way – Nikita Pestrov Aug 17 '12 at 07:21
  • 1
    Almost a decade later this was still very helpful, thanks so much. – Danilo Campos Jan 22 '21 at 00:31