Given the following contrived example:
I would like to query my data for all objects that are either cats or dogs. I want the result set ordered by name regardless of species, so fetching all cats then fetching all dogs won't do. I want to do this in a single query.
One way to do this would be to add a petType field to Pet, give every record a petType value that identifies the sub-entity it belongs to, then query like so:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Pet"
inManagedObjectContext:myMOC];
[fetchRequest setEntity:entity];
// petType values: 1 = dog, 2 = cat, 3 = goldfish. Yuk.
NSPredicate *p = [NSPredicate predicateWithFormat:@"petType = 1 OR petType = 2"]
[fetchRequest setPredicate:p];
// etc...
But the mere thought of doing it that way makes me shudder. Is there a better way?
Update: Thanks to all those who've replied - there are some really good, well-thought out solutions here and I appreciate all of them.
To give this some context, the real data model is a little more complex than this (aren't they always), but it's pretty well organised. I've designed more than my fair share of data schemas in my time and I'm happy that the entities and their relationships are well considered. This issue has come about because (to extend the already shaky contrived example) the client originally wanted:
So far, so good. But they also want a view showing a combined list of all cats and dogs "because little girls like cats and dogs". (Initially it was cats and goldfish, for the same reason.) There isn't really a way to naturally group that subset of the concrete entities; it's really rather arbitrary.
So far, Dave Dribin's "abstract intermediate entity" approach seems like the cleanest solution, although in my case I think it would feel somewhat artificial; really the only way you could truthfully label the intermediate entity would be as "ThingLittleGirlsLike"! :)
As you've found out, you cannot use entity.name
in your fetch predicate for SQLite stores (you can use it on other store types). You can add a petType
, as you suggest, which works well enough, but makes me shudder, too. As an alternative, you could fetch all Pets
, and then filter the fetched results based on entity.name
. But that's a bit inefficient, since you're loading more entities than you need and your doing in-memory filtering that SQLite could be doing on your behalf.
I think the real question is: what are you trying to do? If you really need to fetch Cats
and Dogs
without Goldfish
, then your model should reflect that. You could insert a FourLeggedPet
abstract entity as a parent of Cat
and Dog
. Then, in your fetch request, use FourLeggedPet
as the entity with setIncludesSubentities:YES
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With