Repository navigation
Replies: 3 comments 5 replies
|
Hi @tiendq, I'm not sure I understand how this grouping is supposed to work. You want to group reminders by their title and then order those sections by how many reminders are in each section? So something like this: ? |
This comment was marked as low quality.
This comment was marked as low quality.
|
Write a custom struct RemindersByListSize: FetchKeyRequest {
struct Section: Identifiable, Sendable {
var list: RemindersList
var reminders: [Reminder]
var id: RemindersList.ID { list.id }
}
func fetch(_ db: Database) throws -> [Section] {
let rows = try Reminder
.join(RemindersList.all) { $0.remindersListID.eq($1.id) }
.order { reminder, list in
(
Reminder.where { $0.remindersListID.eq(list.id) }.count().desc(),
list.title.asc(),
list.id.asc(),
reminder.title.asc()
)
}
.select { ($1, $0) }
.fetchAll(db)
// Rows arrive grouped by list, so consecutive rows with the same list are one section.
var sections: [Section] = []
for (list, reminder) in rows {
if sections.last?.list.id == list.id {
sections[sections.count - 1].reminders.append(reminder)
} else {
sections.append(Section(list: list, reminders: [reminder]))
}
}
return sections
}
}Use it with @Fetch(RemindersByListSize()) var sections = []
List {
ForEach(sections) { section in
Section(section.list.title) {
ForEach(section.reminders) { reminder in
Text(reminder.title)
}
}
}
}The generated query ends with: ORDER BY (SELECT count(*) FROM "reminders" WHERE (("reminders"."remindersListID") = ("remindersLists"."id"))) DESC,
"remindersLists"."title" ASC, "remindersLists"."id" ASC, "reminders"."title" ASCWith Personal (4), Business (3) and Urgent (1) reminders it returns Personal, Business, Urgent. After inserting 3 more Business reminders it re-sorts to Business (6), Personal (4), Urgent (1) with no manual reload, because
The subquery counts every reminder in the list, so a Tested with SQLiteData 1.12.1 and swift-structured-queries 0.39.2 on Swift 6.3.3 (macOS). |
Uh oh!
There was an error while loading. Please reload this page.
Example is from here.
Sections are ordered ascending by list title, how to order sections by their item count?
Thanks,
All reactions