NSPredicate filter to-Many with child object property

丶灬走出姿态 提交于 2019-12-11 03:56:07

问题


I have what I thought was a simple problem. I am attempting to filter some core data where I have a Parent object which has a to-many relationship with a child object and that child object has a string id. I want to get all the parent objects where no child object has a specific id.

I have tried !(ANY... LIKE) as well as !(ANY..==) and NONE with like and == and ALL children.id != otherid

My querying looks like:

NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Parent"];

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"NONE children.id LIKE %@",otherID];
[fetchRequest setPredicate: predicate];
NSError* error;
NSArray* allParents = [[DataManager context] executeFetchRequest:fetchRequest error:&error];
//sanity check the predicate
for (Parent* p in allParents) {
    for (Child* c in p.children) {
        if([c.id isEqualToString:otherID]){
            NSLog(@"PREDICATE FAIL!");
        }
    }
}

Am I missing something with NSPredicate? Is this type of filtering allowed for CoreData? Better solution?


回答1:


I found a similar question although not easily apparent. It turns out the answer is the tricky SUBQUERY. Here is what led me on the chase:

NSPredicate Aggregate Operations with NONE

and an more open explanation about SUBQUERY here:

http://funwithobjc.tumblr.com/post/2726166818/what-the-heck-is-subquery

The resulting predicate is:

//in children get a $child and group all the $child objects together
//where the ids match, if that groups count is 0 we know 
//the parent has no child with that id
[NSPredicate predicateWithFormat:
   @"SUBQUERY(children, $child, $child.id == %@).@count == 0",objectId];


来源:https://stackoverflow.com/questions/20235381/nspredicate-filter-to-many-with-child-object-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!