Retrieving count of a core data relation
I searched high and low but I couldn't find exactly what I was looking
for. My question is similar to this, but slightly different:
Core Data - Count of Related Records
Let's say I have a Car entity which has a one to many relation with a
Person entity. This means that the car could have multiple people driving
it, but each person drives only one car.
I want to be able to execute only one predicate wherein I could achieve
the following:
All cars which are 'red'.
Return only the 'Year' and 'Color' attributes of the matching car.
Return a count of how many people are driving this car (i.e the size of
the NSSet of People inside each resulting Car).
Is it possible to do all this with one query?
I know how to do this with multiple queries. I would just use
setPropertiesToFetch and use a filtered predicate to achieve 1 and 2
above. I would then perform another count query (countForFetchRequest) on
the Persons entity for every car to find how many Person(s) drive each
car.
The key is the 3rd requirement above. I want to do everything in one
predicate and I don't want to bring all of the Person entity objects into
memory (performance) on the initial query. Furthermore it hurts to call
another countForFetchRequest query for each car.
What's the best way to do this?
Thanks!
No comments:
Post a Comment