Fetch the last record by date in SwiftData

60 Views Asked by At

I have a @Model class that has an array of items which is also persisted in the database with a relationship. Is there a way to fetch the last record by date at the database level instead of fetching all records and then getting the max date

here is what I am doing now and it is slow and I am looking for a better way

    let fetchDescriptor = FetchDescriptor<Item>(predicate: #Predicate {$0.tag?.persistentModelID == id}, sortBy: [SortDescriptor(\.date)])
 let items = try! modelContext.fetch(fetchDescriptor)
                    let lastItem = items.last!

I tried with fetchDescriptor.fetchLimit = 1, but it did not work and it was giving me some random item.

1

There are 1 best solutions below

0
Joakim Danielson On BEST ANSWER

Use reverse sort order with a fetch limit to only fetch the latest object

var fetchDescriptor = FetchDescriptor<Item>(predicate: { 
    $0.tag?.persistentModelID == id 
}, sortBy: [SortDescriptor(\.date, order: .reverse)])
fetchDescriptor.fetchLimit = 1