views:

43

answers:

2

I have a core data model, using the database store, that contains entities with classic parent/child relationships. Each parent has a number of children, each child a single parent, creating a multi-level hierarchy.

What I would like to do is use a predicate in a fetch request to return a list of all the entities between a given entity and the root.

If I was doing this in code I'd work my way up the 'parent' chain till I hit the root entity, but I'd like to do this in a predicate so that the search stays 'in the database'. This will be part of a search an so needs to be relatively fast.

Is this possible?

A: 

I dont think it's possible to do this in a single round trip using a parent/child relationship. The are other methods, however. If you're concerned about performance (and have measured it to verify this is actually a problem for your average data set) you might find this helpful: Storing Hierarchical Data in a Database

Joshua Nozzi
+2  A: 

Predicates are to hardwired to transverse an unknown number of object in a relationship graph. You have to tell it concretely what entities and relationships to traverse. You can't say, "traverse relationship so-and-so until you hit a nil."

Premature optimization is the root of all evil. I wouldn't worry about the speed of traversing relationships in live objects. Core Data is much faster than you might expect at such things. To optimize in this case, set to fetch as faults so no data is loaded only relationships and I don't think you will have speed issues.

As an aside, watch your nomenclature, entities are to managed objects as classes are to instances. Entities are abstract, managed objects concrete. Entities are attributes only of the data model. In this case for example, you might have only one self-referencing entity in the data model which could be used to create a graph of millions of managed objects.

You can find parent entities just like you find super classes but that wasn't actually what you were asking about.

TechZen
Thanks,good point about the entity/managed object gaffe. At the start of your answer, did you mean to write 'not hardwired'? I agree with your view on premature optimization however in this case I think doing it in the predicate would have been a neater solution with speed and memory savings. Not a good solution if it can't be done though! thanks for your help and time.
oldbeamer