Regan
Regan

Reputation: 1497

Filter a Realm database by matching on tags

I'm using Realm Swift. I have a database full of Document objects, each of which has a List of Tag objects stored as a property. Given one or more tags, how can I get the set of Document objects that match?

My first thought was to filter with an NSPredicate SUBQUERY, but it appears that isn't supported yet.

I also figured I could maintain a list on each Tag object of all of the Document objects that have been labelled with it, and then join the lists of each selected Tag. But I don't see a way to do that in Realm either.

Upvotes: 0

Views: 1013

Answers (1)

nRewik
nRewik

Reputation: 9148

Your realm model should be like this,

class Document:Object{
    let tags = List<Tag>()
    //...
}

and then you can filter documents by tag using ANY keyword,

let realm = Realm()
var documentsFilteredByTag = realm.objects(Document).filter("ANY tags.id = '\(tagID)'")

Upvotes: 2

Related Questions