2017-02-22 25 views
5

我想從LoopBack應用程序通過REST-Api從特定模型查詢記錄。另外我想通過包含過濾器包含相關的對象。 這工作正常,但返回所有相關的對象。是否可以限制它們,也可以通過相關對象的域來排序它們?如何限制環回中包含過濾器的關係記錄?

型號:

- DEPARTMENT 
    Fields: 
     - id 
     - name 
     - ... 
    Relations_ -> hasMany: Messages 
    Relations_ -> hasMany: Members 

- MESSAGE 
    Fields: 
     - id 
     - senderId 
     - body 
     - ... 

- MEMBER 
    Fields: 
     - id 
     - email 
     - ... 

查詢:

我想要實現的是查詢所有部門與他們的所有成員,但只能通過一個特定領域(創建時間戳)訂購的最後一條消息。

第一種方法可能是一個GET請求平原查詢字符串的變體:

http://loopback-server:3000/api/departments?filter[include]=members&filter[include]=messages 

這將返回所有部門的所有信息和所有成員。但是,我想返回的消息的數量限制爲最後一個(或最後5也好,都被消息模型的特定字段排序

我也試過jsonfied查詢語法:

http://loopback-server:3000/api/departments?filter={"include":{"relation": "messages","limit":1}} 

不幸的是,「極限」參數在這裏不用於消息關係

以下變體將只返回第一個部門,意味着limit-param應用於部門模型而不是關係模型。

http://loopback-server:3000/api/departments?filter={"include":{"relation": "messages"},"limit":1} 

然後我發現了範圍 -parameter 並試用了此:

http://loopback-server:3000/api/departments?filter={"include":{"relation": "messages","scope":{"limit":1, "skip":0}}} 

這給出了一個非常奇怪的結果。這將省略與部門有關的所有消息,而不是一條返回一條消息的具體記錄(它已超過10條),我期望的。刪除範圍參數表明部門確實每個都有很多消息。

(我知道的URL與這些特殊字符,如參數{「」}需要進行網址編碼,我離開它的清潔這裏更好的可讀性。)

我的問題:

如何用單個請求實現該查詢?

+1

請看看https://loopback.io/doc/en/lb3/Include-filter.html#include-with-filters –

回答

2

無法通過屬性查詢關係(還)。至於極限,你與範圍最後的方法應該是修改了一點:

"scope":{{"include":{"relation": "messages","limit":1, "skip":0}}} 

在這裏,你可以通過它們的屬性的關係瞭解查詢:

https://github.com/strongloop/loopback/issues/517

+0

不能相信! – octavian

1

我不知道是什麼,你的版本都在,但對於Loopback 3

你可以這樣做..

include: { 
    { 
     relation: 'Messages', // include the messages object 
     scope: { // this is where you do a normal filter 
      where: {<whatevercondition>}, 
      order: "<fieldname> <ASC/DESC>", 
      limit:1, 
      include:{ 
       //yes, you can include 3rd level relation as well. 
      } 
     } 
    }, 
    { 
     relation: 'Members', // include the Members object 
     scope: { // further filter the related model 
      order: "<fieldname> <ASC/DESC>", 
      limit: <whateverlimityoument> 
     } 
    } 
} 
相關問題