Reputation: 1015
I'm trying to recreate a has_many :through relationship (like in Rails) with Objective-C, if Core Data is backed by SQLite, this must be possible right? <rant>
I could write the raw SQL for this in 2 seconds... </rant>
Anyway, basically here is a sub-set of my schema: TutorGroup ----< Allocation >---- Category, what I need to get is all categories that are allocated to a particular tutor group.
Here is my query so far:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(Allocation, $row, $row.tutor_group == %@ AND $row.category == <CURRENT_ROW>).@count > 0)", tutor_group];
Is there a way to represent the current row's object in a sub-query (where I've written <CURRENT_ROW>
? I've tried using self
but that doesn't work.
Also, I'm assuming where I've put Allocation
is the table name I want to perform the sub query on?
Cheers.
Upvotes: 0
Views: 897
Reputation: 16337
I'm not sure it will work, but try this:
ANY Allocation.TutorGroup = %@
Then pass in your tutor group using predicateWithFormat, and run it on Category.
Upvotes: 2
Reputation: 34185
The standard way in CoreData is to have all the inverse relationships. Then you don't have to use predicates at all.
Having inverse relationships is really recommended... see this official document.
So suppose the entity TutorGroup
has a to-many relationship allocations
, and Allocation
has a to-one relationship category
.
Then
NSArray* categories = [tutor_group.allocations valueForKeyPath:@"@distinctUnionOfObjects.category"];
See the discussion of collection operators here.
Typically, when you use Core Data, you shouldn't use the knowledge that CoreData is backed by SQLite. That gives you a peace of your mind.
Upvotes: 2