我是微軟Dynamics 365 & Power Platform方面的工程師/顧問羅勇,也是2015年7月到2018年6月連續三年Dynamics CRM/Business Solutions方面的微軟最有價值專家(Microsoft MVP),歡迎關注我的微信公衆号 MSFTDynamics365erLuoYong ,回複455或者20210921可友善擷取本文,同時可以在第一間得到我釋出的最新博文資訊,follow me!
我們做項目中有時候用到層級資料,比較常見的比如行政區劃,員工,産品BOM之類的,常用的Account實體自帶了一個名稱為 Account Hierarchy 的Hierarchy Setting。我們今天來看看如何定義,展示效果和查詢,參考的官方文檔包括但不限于如下:
Query and visualize hierarchically related data
Define and query hierarchically related data
Query hierarchical data
為了友善示範效果,我建立一個行政區域實體,其中一個字段是Lookup字段到本實體,如下:

然後我們到 Hierarchy Settings 裡面區建立一個Hierarchy Setting。
建立時候點選 Mark a relationship as enabled for hierarchies. 在彈出視窗中選中要lookup到自己的那個relationship,點選【Mark hierarchical】按鈕。
成功後可以看到 【Is Hierarchical?】列的值變成了True,然後我們點選【Done】按鈕關閉視窗。
為了更好的展示效果,我造了一些資料,如下:
點選第一列的層級圖示,我展開一個效果如下所示:
然後我們來看下如何查詢下級,我舉個例子,我想查詢湖南省下面所有的行政區劃,包括市和縣,用進階查找是這樣的,我這裡加了一個常用的篩選條件Status Equal Active, 也就是statecode eq 0,這是我們做項目時候查詢一般要加的篩選,以便充分利用預設的啟用/禁用功能。
看到的結果如下,是正确的。
下載下傳下來的這個查詢的FetchXml如下,可以看到用的操作符是 under 。
當然,進階查找界面還支援 Not Under。
這個查詢結果如下,可以看到将湖南省的上級,湖南省本級和廣東省的所有行政區劃都查詢出來了。
這裡下載下傳下來的FetchXml如下:
對于層級資料查詢,雖然進階查找界面隻支援Under和Not Under兩個操作符,如果用程式設計的方式來查詢的話可以支援更多,主要是額外支援above、eq-or-above、eq-or-under、eq-useroruserhierarchy、eq-useroruserhierarchyandteams,官方文檔解釋如下,我就不一一示範了,用到時候自己測試下自然明白。
可以看到用這些查詢操作符可以一次查詢出相關資料,不用遞歸進行查詢,友善很多。
CONDITION OPERATORS FOR HIERARCHICAL DATA
<col>
FetchXML
ConditionOperator
Description
<code>above</code>
<code>Above</code>
Returns all records in referenced record's hierarchical ancestry line.
<code>eq-or-above</code>
<code>AboveOrEqual</code>
Returns the referenced record and all records above it in the hierarchy.
<code>under</code>
<code>Under</code>
Returns all child records below the referenced record in the hierarchy
<code>eq-or-under</code>
<code>UnderOrEqual</code>
Returns the referenced record and all child records below it in the hierarchy
<code>not-under</code>
<code>NotUnder</code>
Returns all records not below the referenced record in the hierarchy
<code>eq-useroruserhierarchy</code>
<code>OwnedByMeOrMyReports</code>
When hierarchical security models are used, Equals current user or user's reporting hierarchy
<code>eq-useroruserhierarchyandteams</code>
<code>OwnedByMeOrMyReportsAndTeams</code>
When hierarchical security models are used, Equals current user and user's teams, or user's reporting hierarchy and their teams