Leo
Leo

Reputation: 1567

Get Records From Parent Table Based On Relationship Table - CoreData

Sorry if title does not make any sense.

Let me explain it a bit further.

I have this CoreData application and I am relatively new in CoreData. I have two tables. One is Budget and one is Spending. So Budget table has a field called TotalBudget. Now I have different rows in Spending Table which user input over the time and this table has a field called Individual Spend.

Now what I am hoping to do is to get only those budgets where Sum of Individual Spend is less than TotalBudget (Budget table). In SQL language it would be something like below

Select BudgetName From Budget Where TotalBudget < (Select Sum(IndividualBudget) From Spend Where BudgetID = Budget.BudgetID)

How can I achieve that in core data? I have the code to retrieve data from one table and I can use NSPredicate to filter records based to BudgetStartDate and BudgetEndDate but how can I achieve something like that.

Thanks

Upvotes: 0

Views: 431

Answers (1)

RyanR
RyanR

Reputation: 7758

Assuming following object model:

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

IndividualSpend
--amount (decimal)

This will get you an array of Budget entities where the spend amount is > budget amount:

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);

Upvotes: 1

Related Questions