Search code examples
swiftrealm

How to get all childs+grandchilds of a specific parent using Realm in Swift?


I have a 3 databases setup like this Parent->Child->Grandchild, so far I could manage to get the child of a specific parent, but couldn't go deeper to another level.

class Parent : Object {
    @objc dynamic var name : String = ""
    let childs = List<Child>()
}

class Child : Object {
    @objc dynamic var name : String = ""
    let grandchilds = List<Grandchild>()
    var giveBirth = LinkingObjects(fromType: Parent.self, property: "childs")
}

class Grandchild : Object {
    @objc dynamic var name : String = ""
    var giveBirth = LinkingObjects(fromType: Child.self, property: "grandchilds")
}

I used this line to count childs:

if let parent = itemsFromParentList?[indexPath.row] {    
    cell.detailTextLabel?.text = "\(parent.childs.count)"
}

But I want to get the total of all childs+grandchilds of a specific parent, like "How many childs and grandchilds do you have?".

Many thanks!!!


Solution

  • Note that the plural of "child" is "children"

    If I understood correctly, you need to flat map the parent's grandchildren, and then count it, then add the children count to it.

    let childrenPlusGrandchildrenCount = parent.childs.flatMap { $0.grandchilds }.count + parent.childs.count