如何将核心数据中相关实体中的记录与临界值进行汇总(计数或求和)?

时间:2014-06-17 04:22:14

标签: ios nsfetchrequest nsexpression

我有2个实体:发票和产品,与" to-many" '产品的关系'来自Invoice(Invoice.products是该发票的产品实体列表)。

我尝试使用汇总查询来检索给定产品在任何发票上开具发票的次数。所以,让我说我有2张发票:

发票1

  • 产品1

  • 产品2

发票2

  • 产品2

  • 产品3

我想要计算产品1已开票的次数。在这种情况下,1。产品2的开票次数是多少? 2.

如果我查询计数:产品1显示的次数,它返回2,因为有2个产品用于发票1,它应该是1.在下面的代码中,谓词过滤器似乎是任何"发票"具有产品1的实体,一旦找到产品,就会计算产品数量,无论产品ID如何:

//Create an aggregate query on Invoice

//create the NSExpression to tell our NSExpressionDescription which attribute we are performing the calculation on
NSExpression *keyExpression = [NSExpression expressionForKeyPath:@"products.quantity"];

//create the NSExpression to tell our NSExpressionDescription which calculation we are performing.
NSExpression *maxExpression = [NSExpression expressionForFunction:@"count:" arguments:[NSArray arrayWithObject:keyExpression]];

NSExpressionDescription *description = [[NSExpressionDescription alloc] init];
[description setName:@"quantityCount"];
[description setExpression:maxExpression];
[description setExpressionResultType:NSDoubleAttributeType];


MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate getManagedObjectContext];


NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Invoice"];
[request setPredicate:[NSPredicate predicateWithFormat:@"(deletedDate == nil) AND (products.id CONTAINS %@)", product.id]];

NSError *error;
[request setPropertiesToFetch:[NSArray arrayWithObject:description]];
[request setResultType:NSDictionaryResultType];

NSArray *results = [context executeFetchRequest:request error:&error];
if (results != nil && results.count > 0)
{
    NSDecimalNumber *quantityCount = [[results objectAtIndex:0] valueForKeyPath:@"quantityCount"];
    NSLog(@"The count for this product is: %@", quantityCount);
}

我的问题是,如何执行仅计算产品1的数量的聚合查询?我觉得我需要以不同的方式或在其他地方为我的获取请求添加条件。任何帮助将不胜感激!

以下是xcode中我的数据模型的链接:

Invoice

Product

1 个答案:

答案 0 :(得分:0)

您可以简单地使用从ProductInvoice的反向(对多)关系。 假设反向关系称为“发票”:

Product *product = ... ; // the product for which you need the # of invoices
NSUInteger *count = [product.invoices count];