How to use sortDescriptor for an attribute in many ways

  • I have Entity Song and Entity Playlist.
  • A playlist can have several songs and songs that can be associated with several playlists.
  • I have a ListToSongs Entity that maintains the order in which songs were added to the playlist. I do not use “ordered relations” in ios5 (I know about its existence, and I need more control over my model), and I save the order in the sortOrder field in the PlayListToSong object. Thus, the circuit is modeled as (relationship names are written in brackets below):

Song (playlists) <<----> (song) ListToSong (playlist) <---- → (songs) List

I want to get all the songs for a given playlist using a fetch request.

The following query is executed in ListToSong. This retrieves all the PlayListToSong objects, and I can use obj.song to get the Song object. Returns data sorted by sortOrder. Works good. (The code snippets below are written using MagicalRecord for short).

songFilter = [NSPredicate predicateWithFormat:@"playlist == %@", filterList]; linkObjs = [FRListToSongs MR_findAllSortedBy:@"sortOrder" ascending:YES withPredicate:songFilter inContext:ctxt]; 

The following query on the Song object fails. If I remove the sort descriptor and just extract it, it will work. So the problem is with the sortDescriptor "playlists.sortOrder", which is trying to sort based on the attribute in the ListToSongs object.

 songFilter = [NSPredicate predicateWithFormat:@"ANY playlists.playlist == %@", filterList]; songs = [FRSong MR_findAllSortedBy:@"playlists.sortOrder" ascending:YES withPredicate:songFilter inContext:ctxt]; 

In plain SQL (below), I try to make a connection between Song and ListToSong and sort by sortOrder field.

 SELECT DISTINCT 0, t0.Z_PK, t0.Z_OPT, t0.ZNAME, t0.ZSEQ FROM ZSONG t0 JOIN ZFRLISTTOSONGS t1 ON t0.Z_PK = t1.ZSONG WHERE t1.ZPLAYLIST = ? order by t1.ZSORTORDER 

How to match the above SQL with coredata syntax and give the correct sortDescriptor?

Note that the only problem is how to get "order by t1.ZSORTORDER" at the end, since I cannot correctly define sortDescriptor. A fetch query works fine without a sort descriptor.

+4
source share
1 answer

Finally, I included the “Approach 1” mentioned above in my question. I got a ListToSong object and used obj.song to get the associated Song object. I used relationshipKeyPathsForPrefetching to prefetch the song object associated with the ListToSong object.

0
source

Source: https://habr.com/ru/post/1433709/


All Articles