An include filter enables you to include results from related models in a query, for example models that have belongsTo or hasMany relations, to optimize the number of requests. See Creating model relations for more information.
The value of the include filter can be a string, an array, or an object.
REST APIYou can also use stringified JSON format in a REST query.
- relatedModel, relatedModel1, and relatedModel2 are the names (pluralized) of related models.
- propertyName is the name of a property in the related model.
Include relations without filtering:
Return all user posts and orders with two additional requests:
Return all post owners (users), and all orders of each owner:
Return all post owners (users), and all friends and orders of each owner:
Return all post owners (users), and all posts and orders of each owner. The posts also include images.
Include with filters
In some cases, you may want to apply filters to related models to be included.
LoopBack supports that with the following syntax (for example):
For real-world scenarios where only users in
$owner roles should have access, use
findById(). For example, the following example uses filters to perform pagination:
Access included objects
In the Node.js API, call
toJSON() to convert the returned model instance with related items into a plain JSON object. For example:
Note the relation properties such as
These examples assume a customer model with a hasMany relationship to a reviews model.
Return all customers including their reviews:
Return all customers including their reviews which also includes the author:
Return all customers whose age is 21, including their reviews which also includes the author: