Isuru
Isuru

Reputation: 31323

Sorting inside a subquery

I have two Realm objects called Chat and ChatMessage. There's a one-to-many relationship between the two.

class Chat: Object {
    dynamic var id: String = ""
    dynamic var createdAt: Date = Date()
    dynamic var creatorId: String = ""
    let chatMessages = List<ChatMessage>()

    override static func primaryKey() -> String? {
        return "id"
    }
}

class ChatMessage: Object {
    dynamic var id: String = ""
    dynamic var chatId: String = ""
    dynamic var createdAt: Date = Date()
    dynamic var read: Bool = false
    dynamic var authorId: String = ""
    dynamic var text: String = ""
    let chat = LinkingObjects(fromType: Chat.self, property: "chatMessages").first

    override static func primaryKey() -> String? {
        return "id"
    }
}

I need to display a list of chats where chats with most recent messages at the top. Like in all chat apps. To do this, I figured I need to sort the Chat objects by the createdAt property value of the ChatMessage objects linked to each chat.

This is what I have up to now.

func getChats() -> Results<Chat> {
    let realm = try! Realm()
    let chats = realm.objects(Chat.self)
    let predicate = NSPredicate(format: "SUBQUERY(Chat, $chat, $chat.chatMessages)", argumentArray: nil)
    return chats.filter(predicate)
}

I don't know how to sort the chatMessages inside the subquery. Or if that's even possible. Searched Realm docs but couldn't find anything. Any help is appreciated. Or any suggestions if there is a better way to go about this.

Upvotes: 2

Views: 238

Answers (1)

TiM
TiM

Reputation: 16011

The filter query is for isolating specific objects, not for actually sorting them. So trying to go about sorting in an NSPredicate isn't really feasible.

There's an issue being tracked in the Realm GitHub now for allowing sorting via to-many child objects. This would in theory eventually mean you could simply do:

let chats = realm.objects(Chat.self).sorted(byKeyPath: "chatMessages.createdAt")

I'd definitely encourage you to add your +1 to that issue so its priority can get bumped up. :)

In the meantime, while not an absolutely amazing solution, you could add an additional Date property to Chat that is simply lastUpdated that copies the date of the very latest ChatMessage object. That way you could sort the Chat objects directly with that.

Upvotes: 1

Related Questions