{"id":3177,"date":"2019-12-14T12:38:34","date_gmt":"2019-12-14T12:38:34","guid":{"rendered":"https:\/\/www.int4.com\/?p=3177"},"modified":"2020-10-20T14:23:56","modified_gmt":"2020-10-20T12:23:56","slug":"abap-cds-recursive-association-using-hierarchy","status":"publish","type":"post","link":"https:\/\/test11988.futurehost.pl\/abap-cds-recursive-association-using-hierarchy","title":{"rendered":"ABAP CDS recursive association using hierarchy"},"content":{"rendered":"

<\/p>\n

Introduction<\/strong><\/h2>\n

In this article, I will show a practical example of self-association in CDS. You will learn how to define a simple hierarchy in your CDS and how to consume it in your ABAP code.<\/span><\/p>\n

\n<\/div><\/p>\n

The problem<\/strong><\/h2>\n

Recently I have faced a quite interesting problem. There is a concept of something like ‘frame contract’. It means that out of this document many others of the same type (or not necessairely) can be created. Let’s take a look at VBFA table (Sales Document Flow). I am interested only in subsequent Sales Orders, therefore I have filtered out only documents of category ‘C’:<\/span><\/p>\n

\"VBFA\"<\/p>\n

What we can see is a ‘chain’ of documents, or even to be more specific – a tree. Let’s take a look at document 24. More friendly and eye-catching representation of the relationship between those documents would be:<\/span><\/p>\n

\"hierarchy\"<\/p>\n

Root parent of the above tree would be document 24 – our frame contract. Below it you will see it’s ‘children’ – subsequent documents. Now imagine that you would like to extract all documents related to your frame contract. Lot’s of twisted ABAP! Maybe there is an easier way of solving this riddle?<\/span><\/p>\n

Gentle solutions<\/strong><\/h3>\n

Yes! Fortunately, there is – we can avoid looping, reading, assigning and dumping.<\/span><\/p>\n

CDS<\/strong><\/h3>\n

We can define a CDS view which would have an association with itself. Let’s take a look:<\/span><\/p>\n

\"CDS\"<\/p>\n

I have defined a view Z_VBFA based on VBFA and added an association to Z_VBFA. As you can see preceding documents will be treated as parents and subsequent ones as children. The cardinality of the above association is [0..1] as there cannot be any multiple parents – one contract can only have one preceding document, however it can have multiple children. In order to allow consumption of such CDS annotation needs to be added:<\/span><\/p>\n

\"hierarchy\"<\/p>\n

It defines parent-child hierarchy and points at our self-association. There is also a second way of defining a hierarchy:<\/span><\/p>\n

\"hierarchy2\"<\/p>\n

I believe that the first one is much nicer. Remember that in that approach you should not use association.<\/span><\/p>\n

Hierarchy<\/strong><\/h3>\n

You can also define a hierarchy object Z_VBFA_HIERARCHY which would look like this:<\/span><\/p>\n

\"VBFA<\/p>\n