128 lines
2.7 KiB
Markdown
Raw Normal View History

# Filters
See the [filters' concepts](../concepts/concepts.md#filters) for details.
::: note
by default, the filters can only be used from `find` endpoints generated by the Content Type Builder and the [CLI](../cli/CLI.md). If you need to implement a filters system somewhere else, read the [programmatic usage](#programmatic-usage) section.
:::
## Available operators
The available operators are separated in four different categories:
2019-07-18 19:28:52 +02:00
- [Filters](#filters)
- [Sort](#sort)
- [Limit](#limit)
- [Start](#start)
### Filters
Easily filter results according to fields values.
2019-07-18 19:28:52 +02:00
- `=`: Equals
- `_ne`: Not equals
- `_lt`: Lower than
- `_gt`: Greater than
- `_lte`: Lower than or equal to
- `_gte`: Greater than or equal to
- `_contains`: Contains
- `_containss`: Contains case sensitive
- `_in`: Matches any value in the array of values
- `_nin`: Doesn't match any value in the array of values
- `_null`: Equals null/Not equals null
#### Examples
Find users having `John` as first name.
`GET /user?firstName=John`
Find products having a price equal or greater than `3`.
`GET /product?price_gte=3`
### Sort
Sort according to a specific field.
#### Example
Sort users by email.
2019-07-18 19:28:52 +02:00
- ASC: `GET /user?_sort=email:asc`
- DESC: `GET /user?_sort=email:desc`
### Limit
Limit the size of the returned results.
#### Example
Limit the result length to 30.
`GET /user?_limit=30`
### Start
Skip a specific number of entries (especially useful for pagination).
#### Example
Get the second page of results.
`GET /user?_start=10&_limit=10`
## Programmatic usage
Requests system can be implemented in custom code sections.
### Extracting requests filters
To extract the filters from an JavaScript object or a request, you need to call the [`strapi.utils.models.convertParams` helper](../api-reference/reference.md#strapiutils).
::: note
The returned objects is formatted according to the ORM used by the model.
:::
#### Example
**Path —** `./api/user/controllers/User.js`.
```js
// Define a list of params.
const params = {
2019-07-18 19:28:52 +02:00
_limit: 20,
_sort: 'email',
};
// Convert params.
const formattedParams = strapi.utils.models.convertParams('user', params); // { limit: 20, sort: 'email' }
```
### Query usage
#### Example
**Path —** `./api/user/controllers/User.js`.
```js
module.exports = {
find: async (ctx) => {
// Convert params.
const formattedParams = strapi.utils.models.convertParams('user', ctx.request.query);
// Get the list of users according to the request query.
const filteredUsers = await User
.find()
.where(formattedParams.where)
.sort(formattedParams.sort)
.skip(formattedParams.start)
.limit(formattedParams.limit);
// Finally, send the results to the client.
ctx.body = filteredUsers;
};
};
```