# Models

# Defining Models

To get started, let’s create a Users model. Models typically live in the app directory.

The easiest way to create a model instance is using the make-sql-model command:

expresswebcli make-sql-model User

If you would like to generate a database migration when you generate the model, you may use the –migration or –m option:

expresswebcli make-sql-model User --m
expresswebcli make-sql-model User --migration

# Model Conventions

Now, let’s look at an example User model, which we will use to retrieve and store information from our users database table:

# Examples

class User extends DB_MODEL {
  static get tableName() {
    return "userTable";
  }
}

module.exports = User;

# Retrieving Models

Once you have created a model and its associated database table, you are ready to start retrieving data from your database. Think of each model as a powerful query builder allowing you to fluently query the database table associated with the model. For example:

let User = require("@model/User");

const users = await User.query().findById(2);

# Adding Additional Constraints

The query() method will return all of the results in the model’s table. Since each model serves as a query builder, you may also add constraints to queries, and then use the get method to retrieve the results:

const users = await User.query()
  .select("age", "firstName", "lastName")
  .where("age", ">", 40)
  .where("age", "<", 60)
  .where("firstName", "Jennifer")
  .orderBy("lastName");