Page Contents

include过滤器可以使得你在一个查询结果中include到相关的模型。 for example models that have belongsTo or hasMany relations, to optimize the number of requests.  See Creating model relations for more information.

include过滤器的值可以是字符串,数组,或者一个对象。

REST API

filter[include][_relatedModel_]=_propertyName_可以在REST query中使用stringified JSON format

Node API

{include: '_relatedModel_'}
{include: ['_relatedModel1_', '_relatedModel2_', ...]}
{include: {_relatedModel1_: [{_relatedModel2_: ‘_propertyName_’} , ‘_relatedModel_’]}}
```Where:

*   _relatedModel_, _relatedModel1_, 和 _relatedModel2_ 是相关模型的名字(复数形式)。
*   _propertyName_ 是相关模型的属性名。

### 例子

#### 没有在Include中使用过滤器

<div class="sl-hidden"><strong>REVIEW COMMENT from $paramName</strong><br>Include examples from iCars. <strong>Problem</strong>: Need to create reservations to see any related models?</div>

`User.find({include: 'posts'}, function() { ... });`

返回所有用户的帖子和订单:

`User.find({include: ['posts', 'orders']}, function() { ... });`

返回所有帖子的作者和作者的所有订单:

`Post.find({include: {owner: ‘orders’}}, function() { ... });`

返回所有帖子的作者,作者的所有朋友和作者的所有订单:

`Post.find({include: {owner: [‘friends’, ‘orders’]}}, function() { ... });`

返回所有帖子的作者,作者的所有帖子和作者的所有订单。帖子同样还include了图片。

`Post.find({include: {owner: [{posts: ‘images’} , ‘orders’]}}, function() { ... });`

#### 在Include中使用过滤器

在某些情况下,你想要对include的模型使用过滤器。LoopBack使用下面的语法支持在include中使用过滤器:

Post.find({ include: { relation: ‘owner’, // include作者 scope: { // further filter the owner object fields: [‘username’, ‘email’], // 只显示username和email这两个字段 include: { // include作者的订单 relation: ‘orders’,  scope: { where: {orderId: 5} // 只选择orderId为5的订单 } } } } }, function() { … }); ```

REST 例子

These examples assume a customer model with a hasMany relationship to a reviews model. 

Return all customers including their reviews:

/customers?filter[include]=reviews

Return all customers including their reviews which also includes the author:

/customers?filter[include][reviews]=author

Return all customers whose age is 21, including their reviews which also includes the author:

/customers?filter[include][reviews]=author&filter[where][age]=21

Return first two customers including their reviews which also includes the author

/customers?filter[include][reviews]=author&filter[limit]=2

Return all customers including their reviews and orders

/customers?filter[include]=reviews&filter[include]=orders