user2734823
user2734823

Reputation: 157

NSPredicate fetch other entities using an entity's relationship

Alright, here is a piece of my model:

enter image description here

I have a TableViewController which is being populated using a NSFetchedResultsController. In the TableViewController, I want to display all Songs that are a part of a specific playlist. I was hoping to achieve this by somehow fetching all Songs entities that the playlistSongs relationship points to. This TableViewController has a reference a playlist object (although I doubt that will help me here).

My difficulty has been setting up the predicate.

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Playlist"];
    request.predicate = [NSPredicate predicateWithFormat:@"(self.playlistSongs)"];

Upvotes: 0

Views: 1553

Answers (1)

Martin R
Martin R

Reputation: 540065

First of all, if you want to display Songs then you have to create a fetch request on the "Song" entity:

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Song"];

To restrict the result to the songs of a given playlist, use the relationship from "Song" to "Playlist". This is a to-many relationship, so you have to specify "ANY":

request.predicate = [NSPredicate predicateWithFormat:@"ANY playListIAmIn == %@", selectedPlaylist];

Upvotes: 2

Related Questions