In my app I'm trying to list the four most popular products.
The product popularity is determined by the total quantity in orders.
The query below is to illustrate what I'm trying to do:
SELECT TOP 4 SUM(quantity) as sumQuantity, Product
FROM [Order]
GROUP BY Product
ORDER BY 1 DESC
The code below is my approach to getting it in a fetch request against my Core Data model:
// Create an expression to sum the order quantity
NSExpressionDescription *sumExpression = [[NSExpressionDescription alloc] init];
sumExpression.name = @"sumQuantity";
sumExpression.expression = [NSExpression expressionWithFormat:@"@sum.%K", OrderAttributes.quantity];
sumExpression.expressionResultType = NSInteger32AttributeType;
// Create the fetch request
NSFetchRequest *request = [Order createFetchRequest];
request.resultType = NSDictionaryResultType;
request.propertiesToFetch = @[OrderRelationships.product, sumExpression];
request.propertiesToGroupBy = @[OrderRelationships.product];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:sumExpression.name ascending:NO]];
request.fetchLimit = 4;
My problem is the sortDescriptor, it only seems to allow direct properties of Order (app exception).
The sort is extremely important, because it determines which four records will be returned.
Note: I'm using MagicalRecord and Mogenerator. I've removed the class prefixes.
Unfortunately, NSSortDescriptor
wants an actual property to sort on, not dynamically calculated field. Depending on your situation, you would want to either save required counter on a model itself and sort by it, or fetch the whole graph and sort it in memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With