Skip to main content
Version: 1.0.4

Include

The include filter allows you to include related models in your query results. This filter enables the retrieval of data from associated models alongside the primary model, optimizing data access and reducing the need for multiple queries.

Basic Usage

The include filter is specified as an array of objects, where each object represents a related model to include. These objects can specify the relation name and an optional scope that applies additional filters to the included data.

warning

Never make use of the include filter for large datasets, the include filter is meant to ideally retrieve only one result.

Syntax

  • relation: A string that specifies the name of the relation.
  • scope: An object that defines additional filters to apply to the included model, using the where, sort, and limit syntax.

Examples

Simple Include

{
"include": [
"orders"
]
}

This example includes the orders related to the primary model in the query results.

Specifying Relation with Scope

{
"include": [
{
"relation": "orders",
"scope": {
"where": {
"status": "completed"
},
"sort": {
"date": -1
},
"limit": 5
}
}
]
}

This configuration includes the orders related to the primary model, applying a filter to only include completed orders, sorting them by date in descending order, and limiting the results to the last 5 orders.

Including Multiple Relations

{
"include": [
"orders",
{
"relation": "customer",
"scope": {
"where": {
"active": true
},
"sort": {
"lastName": 1
},
"limit": 1
}
}
]
}

This will include orders and customer related to the primary model. For customer, it applies a filter to include only active customers, sorts them by last name in ascending order, and limits the results to the first record.

Notes

  • The inclusion of related models can increase the complexity and response time of queries, particularly with multiple or nested relations.
  • The scope allows the use of any previously defined query filters such as where, sort, and limit.

Conclusion

The include filter provides a powerful way to enhance data retrieval by fetching related models along with the primary query results. This functionality helps in reducing network overhead and simplifies client-side data handling by gathering comprehensive datasets in a single query.