Realm: In a one to many Relation ship, how to get the records based on a Category in this example

391 views Asked by At

User can create a Category and then add a Bookmark to a category

Here is the Category class

class Category: RLMObject {
 dynamic var name = ""
}

A one-to-many relationship is created by declaring the property of type RLMObject(Category)

class Bookmark: RLMObject {
  dynamic var name = ""    
  dynamic var category = Category()
}

There is an API to get all the Bookmarks like this:

Bookmark.allObjects().arraySortedByProperty("name", ascending: true)

I have created a Category with name "stackoverflow" and it has several bookmarks

Now I want to get all the Bookmarks belonging to a specific Category named "stackoverflow". How do I do this?

1

There are 1 answers

0
Thomas Goyne On
let category = Category.objectsWhere("name == 'stackoverflow'").firstObject() as! Category?
if let category = category {
    let bookmarks = category.linkingObjectsOfClass("Bookmark", forProperty: "category")
}