請求書からの「製品」の「対多」関係に関連する請求書と製品の2つのエンティティがあります(Invoice.productsは、その請求書の製品エンティティのリストです)。
集計クエリを使用して、特定の製品が請求書で請求された回数を取得しようとしています。では、2 つの請求書があるとします。
請求書 1
製品 1
製品 2
請求書 2
製品 2
製品 3
そして、製品 1 が請求された回数のカウントが必要です。この場合、1. 製品 2 が請求された回数は? 2.
商品 1 が表示される回数のカウントを照会すると、請求書 1 には 2 つの商品があり、1 である必要があるため、2 が返されます。 " 製品 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内でどのように見えるかへのリンクは次のとおりです: