These docs are for v0.12. Click to read the latest docs for v0.16.

The Query object allows querying the underlying database using a model.

let users = try Query<User>().filter("age", .greaterThan, 21).all()

Model Types

You can use the Query methods directly on a model's type.

let users = User.filter("age", .greaterThan, 21).all()

Model Instances

Instances that conform to model have the methods save(), delete().

let user = User(name: "John", age: 25)
try user.save()

The above user is created, then saved.

guard let user = User.find(1) else {
    throw Abort.badRequest
}
user.name = "Jane"
try user.save()

The above user has the name changed and updated.

guard let user = User.find(1) else {
    throw Abort.badRequest
}
try user.delete()

The above user is fetched then deleted.

Comparisons

The following comparisons can be made using the filter() method.

public enum Comparison {
    case equals
    case greaterThan
    case lessThan
    case greaterThanOrEquals
    case lessThanOrEquals
    case notEquals
}

Limit

Limit the amount of results received to less than or equal to the number supplied.

let users = User.filter("name", "Vapor").limit(5).all()

Scope

.in and .notIn operations are supported.

let users = User.filter("id", .in, [1, 2, 3]).all()

Raw Queries

All database drivers come with a raw method. You can cast the database driver to its underlying driver and run raw queries.

if let mysql = app.database.driver as? MySQLDriver {
    let results = mysql.raw("SELECT @@version")
}

Raw queries will not work if you change the underlying database technology.