I have 2 entities: Invoice and Product, that are related with a "to-many" relationship of 'products' from Invoice (Invoice.products is a list of Product entities for that invoice).
I'm trying to use an aggregate query to retrieve the # of times a given product has been invoiced on any invoice. So let's say I have 2 invoices:
Invoice 1
Product 1
Product 2
Invoice 2
Product 2
Product 3
And I want a count of the # of times Product 1 has been invoiced. In this case, 1. # of times Product 2 has been invoiced? 2.
If I query for the count: of the number of times Product 1 shows up, it returns 2, since there are 2 products for Invoice 1, and it should be 1. It seems in the following code, the predicate filters for any "Invoice" entity that has product 1, and once it finds one, it counts up the # of products, REGARDLESS OF THE PRODUCT 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);
}
My Question is, how do I perform an aggregate query that ONLY counts the # of Product 1s? I feel like I need to add criteria to my fetch request in a different way or in another place. Any help would be appreciated!
Here are links to what my data model looks like inside xcode: