我有两个模型练习和练习记录,它们之间有很多关系。现在我想检索一个Practice对象数组,这些对象的关联practiceRecord对象的数量最小但大于零。我写下面的代码,但它没有工作,并在获取请求时发生异常。请有人给出一个优雅的解决方案。提前谢谢。
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Practice"];
request.predicate = [NSPredicate predicateWithFormat:@"practiceRecords.@count > 0"];
[request setResultType:NSDictionaryResultType];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"practiceRecords.@count"];
NSExpression *minExpression = [NSExpression expressionForFunction:@"min:" arguments:[NSArray arrayWithObject:keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName:@"minPracticeRecordTimes"];
[expressionDescription setExpression:minExpression];
[expressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:expressionDescription]];
NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
if (objects == nil) {
// Handle the error.
}
else {
if ([objects count] > 0) {
NSLog(@"Minimum practice record times: %@", [[objects objectAtIndex:0]
valueForKey:@"minPracticeRecordTimes"]);
}
}
答案 0 :(得分:0)
我猜这个问题是在密钥路径中使用聚合函数(practiceRecords.@count
)
如果您考虑将生成的SQL,它将是这样的:
SELECT min(count(practiceRecords)) AS minPracticeRecordTimes
FROM Practice
WHERE count(practiceRecords) > 0
当然无效。
如果您需要执行此操作,可以稍微对您的实体进行反规范化,并将count
字段添加到Practice
,每次添加或删除PracticeRecord
时都会更新该字段,那么你可以使用直接获取请求。