Beau D'Amore
Beau D'Amore

Reputation: 3392

How do I fetch rows from one Entity based on their relationship to another?

I have two entities: Track: createdDate

Location: altitude ...(7 more attributes in 'Location')

Track has one attribute 'createdDate' with a To-Many to Location.

I need to select back all locations where the Track.createdDate == "whatever-date-i-want" (In SQL it's a join, easy to do.) Here I'm not sure what to do...

The Location entity does NOT have a 'createdDate' attribute since I believe foreignKeys are handled by CoreData itself. Data is going in perfectly if I view the sqlite file, I can see a bunch of locations for every one track (as the GPS plops them into CD)

I am guessing it's a special way of doing a predicate. I tried this following line to no avail:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(Track.createdDate == %@)", currentTrack.createdDate];

but it didn't work. I also tried putting a property in there like so:

@property (nonatomic,retain) Track *lookupTrack;

and trying:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(lookupTrack.createdDate == %@)", currentTrack.createdDate];

also to no avail... ideas? Thanks

EDIT: just now I tried:

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(ANY track.createdDate == %@)", currentTrack.createdDate];

which gave me the error 'keypath createdDate not found in entity '

AND

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(ALL track.createdDate == %@)", currentTrack.createdDate];

which gave me the error 'Unsupported predicate (null)'

EDIT: here are some screenshots enter image description here

enter image description here

Upvotes: 0

Views: 132

Answers (2)

Beau D'Amore
Beau D'Amore

Reputation: 3392

I apologise... it was my sort ...

I had

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"createdDate" ascending:NO];

where it should have been

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"track.createdDate" ascending:NO];

Upvotes: 0

Martin R
Martin R

Reputation: 539845

You have to define the "inverse relationship" from "Location" to "Track" in the Core Data model inspector.

  • Define a to-one relationship from "Location" to "Track", call it "track".
  • Define "track" as inverse relationship to the to-many relationship from "Track" to "Location".

Then the predicate would be

[NSPredicate predicateWithFormat: @"track.createdDate == %@", currentTrack.createdDate]

Upvotes: 1

Related Questions