Skip to content

How to sort results by count aggregate #1273

Answered by groue
gshaw asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @gshaw,

Yes, Column("bookCount") gets qualified with the author table whenever it enters a request of authors that involves other tables. This resolves ambiguities whenever two tables have a column with the same name. In case of bookCount, there is no such ambiguity, but columns like id or creationDate could well be, so columns are generally qualified.

To get a naked bookCount that is never qualified, use Column("bookCount").detached:

struct AuthorInfo: Decodable, FetchableRecord {
    var author: Author
    var bookCount: Int
}

let request = Author
    .annotated(with: Author.books.count)
    .order(Column("bookCount").detached.desc)
let authorInfos: [AuthorInfo] = try AuthorInfo.f…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@gshaw
Comment options

@groue
Comment options

groue Sep 4, 2022
Maintainer

Answer selected by gshaw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants