Vapor 3/Fluent for Postgres: How do I make a SELECT DISTINCT query?

Viewed 601

I'd like to query a model such that Fluent generates SQL that looks like this:

SELECT DISTINCT ON(<my columns>) * FROM my_table...

How do I do that?

1 Answers

Sigh.

So, ended up having to use a raw query. You can do the same with:

let distinctModels = req.withPooledConnection(to: .psql) { (conn) -> Future<[MyModel]> in
    conn.raw("SELECT DISTINCT ON(<my columns>) * FROM <my_table> INNER JOIN <another_table> ON <some_condition> WHERE <conditions>")
        .all(decoding: MyModel.self)
}

Where req is of type Request. The function withPooledConnection will return a future of your models – just make sure you decode them!

Related