# Models

# Concept

Models are a representation of the database's structure and lifecycle. They are split into two separate files. A JavaScript file that contains the lifecycle callbacks, and a JSON one that represents the data stored in the database and their format. The models also allow you to define the relationships between them.

Path β€” ./api/restaurant/models/Restaurant.js.

module.exports = {
  // Before saving a value.
  // Fired before an `insert` or `update` query.
  beforeSave: (model, attrs, options) => {},

  // After saving a value.
  // Fired after an `insert` or `update` query.
  afterSave: (model, attrs, options) => {},

  // ... and more
};

Path β€” ./api/restaurant/models/Restaurant.settings.json.

{
  "connection": "default",
  "info": {
    "name": "restaurant",
    "description": "This represents the Restaurant Model"
  },
  "attributes": {
    "cover": {
      "collection": "file",
      "via": "related",
      "plugin": "upload"
    },
    "name": {
      "default": "",
      "type": "string"
    },
    "description": {
      "default": "",
      "type": "text"
    }
  }
}

In this example, there is a Restaurant model which contains two attributes cover, name and description.

# Where are the models defined?

The models are defined in each ./api/**/models/ folder. Every JavaScript or JSON file in these folders will be loaded as a model. They are also available through the strapi.models and strapi.api.**.models global variables. Usable everywhere in the project, they contain the ORM model object that they are refer to. By convention, models' names should be written in lowercase.

# How to create a model?

TIP

If you are just starting out it is very convenient to generate some models with the Content Type Builder, directly in the admin interface. You can then review the generated model mappings on the code level. The UI takes over a lot of validation tasks and gives you a fast feeling for available features.

Use the CLI, and run the following command strapi generate:model restaurant name:string description:text. Read the CLI documentation for more information.

This will create two files located at ./api/restaurant/models:

  • Restaurant.settings.json: contains the list of attributes and settings. The JSONΒ format makes the file easily editable.
  • Restaurant.js: imports Restaurant.settings.json and extends it with additional settings and lifecycle callbacks.

TIP

when you create a new API using the CLI (strapi generate:api <name>), a model is automatically created.

# Model settings

Additional settings can be set on models:

  • connection (string) - Connection's name which must be used. Default value: default.
  • collectionName (string) - Collection's name (or table's name) in which the data should be stored.
  • globalId (string) -Global variable name for this model (case-sensitive).

Path β€” Restaurant.settings.json.

{
  "connection": "mongo",
  "collectionName": "Restaurants_v1",
  "globalId": "Restaurants",
  "attributes": {}
}

In this example, the model Restaurant will be accessible through the Restaurants global variable. The data will be stored in the Restaurants_v1 collection or table and the model will use the mongo connection defined in ./config/environments/**/database.json

TIP

The connection value can be changed whenever you want, but you should be aware that there is no automatic data migration process. Also if the new connection doesn't use the same ORM you will have to rewrite your queries.

# Model information

The info key on the model-json states information about the model. This information is used in the admin interface, when showing the model.

  • name: The name of the model, as shown in admin interface.
  • description: The description of the model.
  • mainField: Determines which model-attribute is shown when displaying the model.

Path β€” Restaurant.settings.json.

{
  "info": {
    "name": "restaurant",
    "description": ""
  }
}

# Model options

The options key on the model-json states.

  • idAttribute: This tells the model which attribute to expect as the unique identifier for each database row (typically an auto-incrementing primary key named 'id'). Only valid for bookshelf
  • idAttributeType: Data type of idAttribute, accepted list of value below. Only valid for bookshelf
  • timestamps: This tells the model which attributes to use for timestamps. Accepts either boolean or Array of strings where first element is create date and second element is update date. Default value when set to true for Bookshelf is ["created_at", "updated_at"] and for MongoDB is ["createdAt", "updatedAt"].
  • uuid : Boolean to enable UUID support on MySQL, you will need to set the idAttributeType to uuid as well and install the bookshelf-uuid package. To load the package you can see this example.

Path β€” User.settings.json.

{
  "options": {
    "timestamps": true
  }
}

# Define the attributes

The following types are currently available:

  • string
  • text
  • richtext
  • integer
  • biginteger
  • float
  • decimal
  • password
  • date
  • time
  • datetime
  • timestamp
  • boolean
  • binary
  • uuid
  • enumeration
  • json
  • email

# Validations

You can apply basic validations to the attributes. The following supported validations are only supported by MongoDB connection. If you're using SQL databases, you should use the native SQL constraints to apply them.

  • required (boolean) β€” if true adds a required validator for this property.
  • unique (boolean) β€” whether to define a unique index on this property.
  • index (boolean) β€” adds an index on this property, this will create a single field index that will run in the background (only supported by MongoDB).
  • max (integer) β€” checks if the value is greater than or equal to the given minimum.
  • min (integer) β€” checks if the value is less than or equal to the given maximum.

Security validations To improve the Developer eXperience when developing or using the administration panel, the framework enhances the attributes with these "security validations":

  • private (boolean) β€” if true, the attribute will be removed from the server response (it's useful to hide sensitive data).
  • configurable (boolean) - if false, the attribute isn't configurable from the Content Type Builder plugin.

# Example

Path β€” Restaurant.settings.json.

{
  ...
  "attributes": {
    "title": {
      "type": "string",
      "min": 3,
      "max": 99,
      "unique": true
    },
    "description": {
      "default": "My descrioption",
      "type": "text",
      "required": true
    },
    ...
  }
}

# Relations

Relations let your create links (relations) between your Content Types.

# Lifecycle callbacks

WARNING

The life cycle functions are based on the ORM life cycle and not on the strapi request. We are currently working on it to make it easier to use and understand. Please check this issue on GitHub.

The following events are available by default:

Callbacks on:

# Example