我有以下CoreData对象模型

现在,我在使用以下条件进行谓词时遇到了问题。
获取所有位于以下位置的DBOpportunity
DBOpportunity.stateCode == 1
和
DBOpportunity.invoiceDate >= GIVEN_DATE
和
DBOpportunityLines.crmAccept == 1或DBOpportunityLines.crmAccept == 3
我已经尝试了很多示例和apple的编程指南,但都不能做到这一点。
发布于 2013-05-24 14:58:10
opportunitylines是一种多对多关系,因此一个DBOpportunity对象有多个DBOpportunityLines对象。假设最后一个条件
DBOpportunityLines.crmAccept == 1或DBOpportunityLines.crmAccept == 3
对于任何相关对象,您都需要一个SUBQUERY:
NSDate *givenDate = ...;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"stateCode == 1 AND invoiceDate >= %@ "
"AND SUBQUERY(opportunitylines, $x, $x.crmAccept == 1 OR $x.crmAccept == 3).@count > 0",
givenDate];备注:不幸的是,SUBQUERY在谓词中的用法很少有文档记录。在NSExpression类引用中有one example。另请参见Quick Explanation of SUBQUERY in NSPredicate Expression。
发布于 2013-05-24 14:14:09
谓词的结构是A && B && (C || D)
设置你的谓词
NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"stateCode == %d", value];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"invoiceDate >= %@", givenDate];cPredicate和dPredicate也是如此。然后先用OR将c和d组合起来
NSArray *cdPredicateArray = @[cPredicate, dPredicate];
NSPredicate *cdPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:cdPredicateArray];然后所有的数据都带有和
NSArray *allPredicateArray = @[aPredicate, bPredicate, cdPredicate];
NSPredicate *allPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:allPredicateArray];如果我误解了您问题,而您的结构是A && B && C || D,那么您必须首先将A、B和C组合(与AND),然后将结果与D(与OR)组合。
发布于 2013-05-24 15:18:15
您还可以获取opportunityLines,然后获取父实体,如下所示:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"opportunityLines" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSDate *yourDate = [NSDate date];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(crmAccept==1 OR crmaccept==3) AND opportunity.stateCode==1 AND opportunity.invoiceDate>=%@", yourDate];
[fetchRequest setPredicate:predicate];
NSError *error;
//So here you have your array of opportunitylines
NSArray *opportunityLines = [context executeFetchRequest:fetchRequest error:&error];
//And this is how you get your opportunity objects
NSArray *opportunities = [opportunityLines valueForKeyPath:@"@distinctUnionOfObjects.opportunity"];https://stackoverflow.com/questions/16728294
复制相似问题