How to fetch a limited number of related models?

40 Views Asked by At

With the ParentModel, I would like to fetch only the most recent 7 ChildModels.

What's the best way to do this?

Relationship

Say you have a relationship set up like so:

@Model
class ParentModel {
    var name: String
    @Relationship(deleteRule: .cascade, inverse: \ChildModel.parent)
    var children: [ChildModel] = []
    
    init(name: String, children: [ChildModel] = []) {
        self.name = name
        self.children = children
    }
}

@Model
class ChildModel {
    var date: Date
    var value: Double
    var parent: ParentModel?
    
    init(date: Date, value: Double, parent: ParentModel? = nil) {
        self.date = date
        self.value = value
        self.parent = parent
    }
}

Example

This is what I would like to achieve, just 7 related rows. So if there were 100 child rows, I would only want the 7 most recent ones.

Animation of screen going from parent to children

GitHub Repo

If you want a working project to try and find or test your solution, I have it here on GitHub.

0

There are 0 best solutions below