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

Models make interacting with your database objects easy. They support finding, saving, deleting, and even preparing the database.

Simple Example

The following example shows a User model.

import Vapor

final class User: Model {
    var id: Value?
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    init(serialized: [String: Value]) {
        name = serialized["name"].string ?? ""
        age = serialized["age"].int ?? 0
    }
}

init(name: String, age: Int)
This method is not required to be a Model, but it allows a convenient way to initialize a new model.

Properties

id
This model has three properties. The first is the id: Value? which is required to be a Model. This will contain the identifier for item in the database. It is of type Value since different types of databases store identifiers differently.

name, age
The next two properties are just for this user. Their names will match the data stored in the database.

Serialized Initialization

init(serialized: [String: Value])
This method is required to be a model. It is called to inflate the Swift version of your model from the database version. If you use defaults, all of the field names should match the property names.

If your properties are non-optional, you must provide a sensible default here in case the database returns NULL or does not include the field when queried.

Serialize

You can customize the way the model serializes to the database by overriding the serialize() method.

func serialize() -> [String : Value?] {
    return [
        "id": id,
        "name": name,
        "age": age
    ]
}

The keys in this method will become the columns in a SQL database or outline the dictionary structure in a NoSQL database.

If you define your own serialization method, you will most likely need to create custom preparations. See the Preparation section for more information.

Querying

All of the methods defined in the Query section can be used on a Model instance or type.

let user = try User.find(1)
try user.delete()

See the query section to learn more.