strapi/docs/3.x.x/en/guides/models.md

692 lines
17 KiB
Markdown
Raw Normal View History

2017-10-10 11:15:24 +02:00
# Models
See the [models' concepts](../concepts/concepts.md#models) for details.
2017-10-10 11:15:24 +02:00
## How to create a model?
2018-02-18 16:17:19 +01:00
> Note: 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.
2017-10-10 11:15:24 +02:00
Use the CLI, and run the following command `strapi generate:model user firstname:string lastname:string`. Read the [CLI documentation](../cli/CLI.md) for more informations.
This will create two files located at `./api/user/models`:
- `User.settings.json`: contains the list of attributes and settings. The JSON format makes the file easily editable.
2017-10-10 11:15:24 +02:00
- `User.js`: imports `User.settings.json` and extends it with additional settings and lifecycle callbacks.
> Note: when you create a new API using the CLI (`strapi generate:api <name>`), a model is automatically created.
## 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.
2017-10-10 11:15:24 +02:00
## Define the attributes
The following types are currently available:
- `string`
- `text`
- `integer`
- `biginteger`
- `float`
- `decimal`
2017-11-28 13:53:08 +01:00
- `password`
2017-10-10 11:15:24 +02:00
- `date`
- `time`
- `datetime`
- `timestamp`
- `boolean`
- `binary`
- `uuid`
- `enumeration`
- `json`
- `email`
2017-10-10 11:15:24 +02:00
2018-02-09 11:02:00 +01:00
#### 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.
- `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.
2017-10-10 11:15:24 +02:00
#### Example
**Path —** `User.settings.json`.
```json
{
"connection": "default",
"info": {
"name": "user",
"description": "This represents the User Model",
"mainField": "email"
2017-10-10 11:15:24 +02:00
},
"attributes": {
"firstname": {
"type": "string"
},
"lastname": {
"type": "string"
},
2018-02-09 11:03:53 +01:00
"email": {
"type": "email",
"required": true,
"unique": true
},
2017-11-28 13:53:08 +01:00
"password": {
2018-02-09 11:03:53 +01:00
"type": "password",
"required": true,
"private": true
2017-11-28 13:53:08 +01:00
},
2017-10-10 11:15:24 +02:00
"about": {
"type": "description"
},
"age": {
2018-02-09 11:03:53 +01:00
"type": "integer",
"min": 18,
"max": 99
2017-10-10 11:15:24 +02:00
},
"birthday": {
"type": "date"
}
}
}
```
## Relations
Refer to the [relations concept](../concepts/concepts.md#relations) for more informations about relations type.
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
### One-way
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
Refer to the [one-way concept](../concepts/concepts.md#one-way) for informations.
2017-10-10 11:15:24 +02:00
#### Example
2018-02-22 18:28:10 +01:00
A `pet` can be owned by someone (a `user`).
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
**Path —** `./api/pet/models/Pet.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
2018-02-22 18:28:10 +01:00
"owner": {
"model": "user"
2017-10-10 11:15:24 +02:00
}
}
}
```
2018-02-22 18:28:10 +01:00
**Path —** `./api/pet/controllers/Pet.js`.
```js
// Mongoose example
module.exports = {
findPetsWithOwners: async (ctx) => {
// Retrieve the list of pets with their owners.
const pets = Pet
.find()
.populate('owner');
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
// Send the list of pets.
ctx.body = pets;
}
}
```
### One-to-one
Refer to the [one-to-one concept](../concepts/concepts.md#one-to-one) for informations.
#### Example
A `user` can have one `address`. And this address is only related to this `user`.
**Path —** `./api/user/models/User.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
2018-02-22 18:28:10 +01:00
"address": {
"model": "address",
"via": "user"
2017-10-10 11:15:24 +02:00
}
}
}
```
2018-02-22 18:28:10 +01:00
**Path —** `./api/address/models/Address.settings.json`.
```json
{
"attributes": {
"user": {
"model": "user"
}
}
}
```
**Path —** `./api/user/controllers/User.js`.
2017-10-10 11:15:24 +02:00
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
2018-02-22 18:28:10 +01:00
findUsersWithAddresses: async (ctx) => {
// Retrieve the list of users with their addresses.
const users = User
2017-10-10 11:15:24 +02:00
.find()
2018-02-22 18:28:10 +01:00
.populate('address');
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
// Send the list of users.
ctx.body = users;
2017-10-10 11:15:24 +02:00
}
}
```
2018-02-22 18:28:10 +01:00
**Path —** `./api/adress/controllers/Address.js`.
2017-10-10 11:15:24 +02:00
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
2018-02-22 18:28:10 +01:00
findArticlesWithUsers: async (ctx) => {
// Retrieve the list of addresses with their users.
const articles = Address
2017-10-10 11:15:24 +02:00
.find()
2018-02-22 18:28:10 +01:00
.populate('user');
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
// Send the list of addresses.
ctx.body = addresses;
2017-10-10 11:15:24 +02:00
}
}
```
### One-to-many
Refer to the [one-to-many concept](../concepts/concepts.md#one-to-many) for more informations.
2017-10-10 11:15:24 +02:00
#### Example
A `user` can have many `articles`, and an `article` can be related to one `user` (author).
2017-10-11 10:51:28 +02:00
**Path —** `./api/user/models/User.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
"articles": {
"collection": "article",
"via": "author"
}
}
}
```
**Path —** `./api/article/models/Article.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
"author": {
"model": "user"
}
}
}
```
**Path —** `./api/user/controllers/User.js`.
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
findUsersWithArticles: async (ctx) => {
2017-10-10 11:15:24 +02:00
// Retrieve the list of users with their articles.
const users = User
.find()
.populate('articles');
// Send the list of users.
ctx.body = users;
}
}
```
**Path —** `./api/article/controllers/Article.js`.
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
findArticlesWithAuthors: async (ctx) => {
2017-10-10 11:15:24 +02:00
// Retrieve the list of articles with their authors.
const articles = Article
.find()
.populate('author');
// Send the list of users.
ctx.body = users;
}
}
```
2018-02-22 18:28:10 +01:00
### Many-to-many
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
Refer to the [many-to-many concept](../concepts/concepts.md#many-to-many).
2017-10-10 11:15:24 +02:00
#### Example
2018-02-22 18:28:10 +01:00
A `product` can be related to many `categories`, so a `category` can have many `products`.
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
**Path —** `./api/product/models/Product.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
2018-02-22 18:28:10 +01:00
"categories": {
"collection": "category",
2018-02-22 18:28:10 +01:00
"via": "products",
"dominant": true
2017-10-10 11:15:24 +02:00
}
}
}
```
2018-02-22 18:28:10 +01:00
> Note: The `dominant` key allows you to define in which table/collection (only for NoSQL databases) should be stored the array that defines the relationship. Because there is no join table in NoSQL, this key is required for NoSQL databases (ex: MongoDB).
**Path —** `./api/category/models/Category.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
2018-02-22 18:28:10 +01:00
"products": {
"collection": "product",
2018-02-22 18:28:10 +01:00
"via": "categories"
2017-10-10 11:15:24 +02:00
}
}
}
```
2018-02-22 18:28:10 +01:00
**Path —** `./api/product/controllers/Product.js`.
2017-10-10 11:15:24 +02:00
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
2018-02-22 18:28:10 +01:00
findProductsWithCategories: async (ctx) => {
// Retrieve the list of products.
const products = Product
2017-10-10 11:15:24 +02:00
.find()
2018-02-22 18:28:10 +01:00
.populate('categories');
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
// Send the list of products.
ctx.body = products;
2017-10-10 11:15:24 +02:00
}
}
```
2018-02-22 18:28:10 +01:00
**Path —** `./api/category/controllers/Category.js`.
2017-10-10 11:15:24 +02:00
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
2018-02-22 18:28:10 +01:00
findCategoriesWithProducts: async (ctx) => {
// Retrieve the list of categories.
const categories = Category
2017-10-10 11:15:24 +02:00
.find()
2018-02-22 18:28:10 +01:00
.populate('products');
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
// Send the list of categories.
ctx.body = categories;
2017-10-10 11:15:24 +02:00
}
}
```
2018-02-22 18:28:10 +01:00
### Polymorphic
The polymorphic relationships are the solution when you don't know which kind of model will be associated to your entry. A common use case is an `Image` model that can be associated to many others kind of models (Article, Product, User, etc).
2018-06-20 18:50:49 +02:00
Refer to the [upload plugin](./upload.md) polymorphic implementation for more informations.
2018-06-20 17:03:10 +02:00
2018-02-22 18:28:10 +01:00
#### Single vs Many
Let's stay with our `Image` model which might belongs to **a single `Article` or `Product` entry**.
> In other words, it means that a `Image` entry can be associated to one entry. This entry can be a `Article` or `Product` entry.
**Path —** `./api/image/models/Image.settings.json`.
```json
{
"attributes": {
"related": {
"model": "*",
"filter": "field"
}
}
}
```
Also, our `Image` model which might belongs to **many `Article` or `Product` entries**.
> In other words, it means that a `Article` entry can relate to the same image than a `Product` entry.
**Path —** `./api/image/models/Image.settings.json`.
```json
{
"attributes": {
"related": {
"collection": "*",
"filter": "field"
}
}
}
```
#### Filter
The `filter` attribute is optional (but we highly recommend to use every time). If it's provided it adds a new match level to retrieve the related data.
For example, the `Product` model might have two attributes which are associated to the `Image` model. To distinguish which image is attached to the `cover` field and which images are attached to the `pictures` field, we need to save and provide this to the database.
**Path —** `./api/article/models/Product.settings.json`.
```json
{
"attributes": {
"cover": {
"model": "image",
"via": "related",
},
"pictures": {
"collection": "image",
"via": "related"
}
}
}
```
The value is the `filter` attribute is the name of the column where the information is stored.
2017-10-10 11:15:24 +02:00
#### Example
2018-02-22 18:28:10 +01:00
A `Image` model might belongs to many either `Article` models or a `Product` models.
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
**Path —** `./api/image/models/Image.settings.json`.
```json
2017-10-10 11:15:24 +02:00
{
"attributes": {
2018-02-22 18:28:10 +01:00
"related": {
"collection": "*",
"filter": "field"
2017-10-10 11:15:24 +02:00
}
}
}
```
2018-02-22 18:28:10 +01:00
**Path —** `./api/article/models/Article.settings.json`.
```json
{
"attributes": {
"avatar": {
"model": "image",
"via": "related"
}
}
}
```
**Path —** `./api/article/models/Product.settings.json`.
```json
{
"attributes": {
"pictures": {
"collection": "image",
"via": "related"
}
}
}
```
**Path —** `./api/image/controllers/Image.js`.
2017-10-10 11:15:24 +02:00
```js
// Mongoose example
2017-10-10 11:15:24 +02:00
module.exports = {
2018-02-22 18:28:10 +01:00
findFiles: async (ctx) => {
// Retrieve the list of images with the Article or Product entries related to them.
const images = Images
2017-10-10 11:15:24 +02:00
.find()
2018-02-22 18:28:10 +01:00
.populate('related');
/*
[{
"_id": "5a81b0fa8c063a53298a934a",
"url": "http://....",
"name": "john_doe_avatar.png",
"related": [{
"_id": "5a81b0fa8c063a5393qj934a",
"title": "John Doe is awesome",
"description": "..."
}, {
"_id": "5a81jei389ns5abd75f79c",
"name": "A simple chair",
"description": "..."
}]
}]
*/
// Send the list of files.
ctx.body = images;
}
}
```
2017-10-10 11:15:24 +02:00
2018-02-22 18:28:10 +01:00
**Path —** `./api/article/controllers/Article.js`.
```js
// Mongoose example
module.exports = {
findArticlesWithAvatar: async (ctx) => {
// Retrieve the list of articles with the avatar (image).
const articles = Article
.find()
.populate('avatar');
/*
[{
"_id": "5a81b0fa8c063a5393qj934a",
"title": "John Doe is awesome",
"description": "...",
"avatar": {
"_id": "5a81b0fa8c063a53298a934a",
"url": "http://....",
"name": "john_doe_avatar.png"
}
}]
*/
// Send the list of users.
ctx.body = articles;
}
}
```
**Path —** `./api/product/controllers/Product.js`.
```js
// Mongoose example
module.exports = {
findProductWithPictures: async (ctx) => {
// Retrieve the list of products with the pictures (images).
const products = Product
.find()
.populate('pictures');
/*
[{
"_id": "5a81jei389ns5abd75f79c",
"name": "A simple chair",
"description": "...",
"pictures": [{
"_id": "5a81b0fa8c063a53298a934a",
"url": "http://....",
"name": "chair_position_1.png"
}, {
"_id": "5a81d22bee1ad45abd75f79c",
"url": "http://....",
"name": "chair_position_2.png"
}, {
"_id": "5a81d232ee1ad45abd75f79e",
"url": "http://....",
"name": "chair_position_3.png"
}]
}]
*/
// Send the list of users.
ctx.body = products;
2017-10-10 11:15:24 +02:00
}
}
```
2018-02-22 18:28:10 +01:00
#### Database implementation
If you're using MongoDB as a database, you don't need to do anything. Everything is natively handled by Strapi. However, to implement a polymorphic relationship with SQL databases, you need to create two tables.
**Path —** `./api/image/models/Image.settings.json`.
```json
{
"attributes": {
"name": {
"type": "string"
},
"url": {
"type": "string"
},
"related": {
"collection": "*",
"filter": "field"
}
}
}
```
The first table to create is the table which has the same name as your model.
```
CREATE TABLE `image` (
`id` int(11) NOT NULL,
`name` text NOT NULL,
`text` text NOT NULL
)
```
> Note: If you've overrided the default table name given by Strapi by using the `collectionName` attribute. Use the value set in the `collectionName` to name the table.
The second table will allow us to associate one or many others entries to the `Image` model. The name of the table is the same as the previous one with the suffix `_morph`.
```
CREATE TABLE `image_morph` (
`id` int(11) NOT NULL,
`image_id` int(11) NOT NULL,
`related_id` int(11) NOT NULL,
`related_type` text NOT NULL,
`field` text NOT NULL
)
```
- `image_id` is using the name of the first table with the suffix `_id`.
- **Attempted value:** It correspond to the id of an `Image` entry.
- `related_id` is using the attribute name where the relation happens with the suffix `_id`.
- **Attempted value:** It correspond to the id of an `Article` or `Product` entry.
- `related_type` is using the attribute name where the relation happens with the suffix `_type`.
- **Attempted value:** It correspond to the table name where the `Article` or `Product` entry is stored.
- `field` is using the filter property value defined in the model. If you change the filter value, you have to change the name of this column as well.
- **Attempted value:** It correspond to the attribute of a `Article`, `Product` with which the `Image` entry is related.
| id | image_id | related_id | related_type | field |
|----|----------|------------|--------------|--------|
| 1 | 1738 | 39 | product | cover |
| 2 | 4738 | 58 | article | avatar |
| 3 | 1738 | 71 | article | avatar |
2017-10-10 11:15:24 +02:00
## Lifecycle callbacks
Refer to the [lifecycle callbacks concepts](../concepts/concepts.md#lifecycle-callbacks) for informations.
2017-10-10 11:15:24 +02:00
The following events are available by default:
Callbacks on `save`:
- beforeSave
- afterSave
Callbacks on `fetch`:
- beforeFetch
- afterFetch
2017-11-29 15:46:28 +01:00
Callbacks on `fetchAll`:
- beforeFetchAll
- afterFetchAll
2017-10-10 11:15:24 +02:00
Callbacks on `create`:
- beforeCreate
- afterCreate
Callbacks on `update`:
- beforeUpdate
- afterUpdate
Callbacks on `destroy`:
- beforeDestroy
- afterDestroy
#### Mongoose
The entry is available through the `model` parameter
2017-10-10 11:15:24 +02:00
**Path —** `./api/user/models/User.js`.
```js
module.exports = {
/**
* Triggered before user creation.
*/
2017-11-29 15:46:28 +01:00
beforeCreate: async (model) => {
// Hash password.
const passwordHashed = await strapi.api.user.services.user.hashPassword(model.password);
2017-11-29 15:46:28 +01:00
// Set the password.
model.password = passwordHashed;
}
}
```
#### Bookshelf
Each of these functions receives a three parameters `model`, `attrs` and `options`. You have to return a Promise.
2017-10-10 11:15:24 +02:00
**Path —** `./api/user/models/User.js`.
```js
module.exports = {
2017-10-10 11:15:24 +02:00
/**
* Triggered before user creation.
*/
2017-11-29 15:46:28 +01:00
beforeCreate: async (model, attrs, options) => {
2018-03-16 15:54:53 +01:00
// Hash password.
const passwordHashed = await strapi.api.user.services.user.hashPassword(model.attributes.password);
2017-11-29 15:46:28 +01:00
2018-03-16 15:54:53 +01:00
// Set the password.
model.set('password', passwordHashed);
2017-10-10 11:15:24 +02:00
}
}
```
## 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 —** `User.settings.json`.
```json
{
"connection": "mongo",
"collectionName": "Users_v1",
"globalId": "Users",
"attributes": {
2017-11-28 13:53:08 +01:00
}
2017-10-10 11:15:24 +02:00
}
```
In this example, the model `User` will be accessible through the `Users` global variable. The data will be stored in the `Users_v1` collection or table and the model will use the `mongo` connection defined in `./config/environments/**/database.json`
> Note: 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.