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
Node API
{include: ['relatedModel1', 'relatedModel2', ...]}
{include: {relatedModel1: [{relatedModel2: ‘propertyName’} , ‘relatedModel’]}}
- relatedModel, relatedModel1, 和 relatedModel2 是相关模型的名字(复数形式)。
- propertyName 是相关模型的属性名。
例子
没有在Include中使用过滤器
Include examples from iCars. Problem: Need to create reservations to see any related models?
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
/customers?filter[include][reviews]=author&filter[limit]=2
/customers?filter[include]=reviews&filter[include]=orders