Post

Replies

Boosts

Views

Activity

Querying data from one-to-many relationship by aggregate in swiftdata
Hi all, I've been struggling a bit with SwiftData, I have a really simple data model but I need to do a fairly complex query over a one-to-many relationship that results in aggregate values. And I want to be able to sort and filter those aggregates. The model looks like this: @Model class Category { var name: String var items = [Item]() } @Model class Item { var added: Date var checked: Date? } In a typical use case I'd expect their to be at most around 50 categories and perhaps 20 items per category. In my UI I would like to be able to sort categories in a couple of ways: by name, by date added and by date checked with a fallback on date added. Also, in my list view I want to be able to list categories and show the checked date of the most recently checked item. I can think of a couple of solutions here, to start of with I can do all the sorting and filtering client-side. In the list view I could retrieve all the categories and then find the most recently checked item per category and go from there. Another solution might be to use a transformable column for the items, because I expect there to be only a few of them per category. The last thing I can think of, that I know how to make is to denormalize the model, and add a checked and added column to the category model. These would have to be updated each time an item is added or checked. All of these solutions sound suboptimal to me. Ideally I would want to add a checked and added column to the category model that are computed in the database using a query. I previously implemented this simple app in Django (Python), where I could easily implement this particular solution, offloading all the sorting and aggregating to the database. So my question is if this is possible in SwiftData and how to do it. If it is not possible what would be the preferred solution? Since the expected amount of data is pretty small I could probably get.away with doing it all in code instead of in queries, but that just doesn't feel right.
0
0
334
Jan ’24