title: How to limit records of relations with include-filter in loopback?
body: <p>I want to query records from a specific model via REST-Api from a <strong>LoopBack</strong>-application. Also i want to include related objects via the include-filter.
  This works fine, but returns ALL related objects. Is it possible to limit them and also to order them by a field of related objects?</p>
  
  <h1>Models:</h1>
  
  <pre><code>-   DEPARTMENT
      Fields:
          - id
          - name 
          - ...
      Relations_ -&gt; hasMany: Messages
      Relations_ -&gt; hasMany: Members
  
  - MESSAGE
      Fields:
         - id
         - senderId
         - body
         - ...
  
  - MEMBER
      Fields:
         - id
         - email
         - ...
  </code></pre>
  
  <h1>Queries:</h1>
  
  <p>What i want to achieve is to query all Departments with all their members, but only the last message ordered by a specific field (created-timestamp).</p>
  
  <p>The first approach could be the plain query-string variant of a GET-Request:</p>
  
  <pre><code>http://loopback-server:3000/api/departments?filter[include]=members&amp;filter[include]=messages
  </code></pre>
  
  <p>This will return all departments with all messages and all members. However, i would like to limit the number of returned messages to the last one (or last 5 or whatever, sorted by a specific field of MESSAGE-model.</p>
  
  <p>I also tried the jsonfied query syntax:</p>
  
  <pre><code>http://loopback-server:3000/api/departments?filter={"include":{"relation": "messages","limit":1}}
  </code></pre>
  
  <p>Unfortunately the "limit"-parameter is not used here for the relation of messages. </p>
  
  <p>The following variant will return only first department, means the limit-param is applied to the departments-model, not the relation model.</p>
  
  <pre><code>http://loopback-server:3000/api/departments?filter={"include":{"relation": "messages"},"limit":1}
  </code></pre>
  
  <p>Then i discovered the <strong>scope</strong>-parameter
   and tried this:</p>
  
  <pre><code>http://loopback-server:3000/api/departments?filter={"include":{"relation": "messages","scope":{"limit":1, "skip":0}}}
  </code></pre>
  
  <p>This gives a really strange result. This ommits all messages related to departments, instead of one specific record returning one message (it has over 10), what i would expect. Removing the scope-parameter shows that the departments indeed has many messages each.</p>
  
  <p><em>(I know that the parameters of an URL with all these special characters like {",:"} need to be url-encoded. I leave it clean here for better readability)</em></p>
  
  <h1>My question:</h1>
  
  <p>How to achieve that query with a single request?</p>