Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to get relationship count in database

I want to know what is the best way to get count of related entities in to-many relationship. Let's say I have a data model that looks like this (simplified), and I want to know the number of passengers for each bus:

data model

Currently I can think of two options:

  1. Add an extra attribute to bus entity called passengerCount which will be updated every time a passenger is added/removed.

  2. Every time the count of passengers needs to be displayed, it's done by fetching the passengers and displaying their count.

Both of my options seem quite inefficient, even though I'm not aware how heavy it is to update/fetch values with core data. For example, imagine doing number 2 for every table view cell.

My question is: What is the best way to do this? A method in NSManagedObject class perhaps (I couldn't find any) or some other way that is more efficient?

like image 779
Aleksi Sjöberg Avatar asked Sep 30 '15 07:09

Aleksi Sjöberg


1 Answers

Three remarks at the very beginning:

A. You should care about efficiency when you have a runtime problem. "Premature optimization is the root of all evil." (Donald Knuth)

B. Who said that all passenger entities has to be fetched? You think of something like this …

[bus.passengers count]

… causing passengers to be fetched. But Core Data supports faulting, so maybe the entities are maybe fetched into fault. (Having only an id, but not the full object.)

C. You can see what Core Data does, when you turn verbose mode on. To do so pass the launch argument

-com.apple.CoreData.SQLDebug 1

To your question itself:

If you really have a problem, you can ask for a count explicitly with -countForFetchRequest:error:.

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"passenger"];
fetch.predicate = [NSPredicate predicateWithFormat:@"bus == %@", bus];
…
NSUInteger count = [context countForFetchRequest:fetch error:NULL]; // Please pass an NSError instance in real world

Typed in Safari.

like image 112
Amin Negm-Awad Avatar answered Nov 03 '22 08:11

Amin Negm-Awad