2011-06-27 65 views
0

對不起,如果標題沒有任何意義。基於關係表從父表中獲取記錄 - CoreData

讓我再解釋一下。

我有這個CoreData應用程序,我在CoreData中是比較新的。我有兩張桌子。一個是預算,一個是支出。所以預算表中有一個名爲TotalBudget的字段。現在我在Spending Table中有不同的行,這是用戶輸入的時間,此表中有一個名爲Individual Spend的字段。

現在我所希望做的只是獲得單個支出總和小於TotalBudget(預算表)的預算。在SQL語言它會像下面

選擇BudgetName 從 預算凡TotalBudget <(SELECT SUM(IndividualBudget)從支出凡BudgetID = Budget.BudgetID)

我怎樣才能做到這一點的核心數據?我有代碼從一個表中檢索數據,我可以使用NSPredicate根據BudgetStartDate和BudgetEndDate過濾記錄,但我怎麼能實現這樣的。

感謝

回答

1

假設以下對象模型:

Budget 
--amount (decimal) 
--spend (relationship to IndividualSpend object) 

IndividualSpend 
--amount (decimal) 

這將讓你的預算實體的數組,其中在支出金額爲>預算金額:

NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; 
fetch.entity = [managedObjectModel objectForKey:@"Budget"]; 
fetch.predicate = [NSPredicate predicateWithFormat:@"[email protected] > amount"]; 

NSError *error = nil; 
NSArray *results = [context executeFetchRequest:fr error:&error]; 
if (error) { 
    NSLog(@"ERROR: %@", error); 
} 
NSLog(@"Results: %@", results); 
+0

非常感謝。完善! – Leo