This is not exactly correct, i see that here you are just overwriting the same previous order field as you go through loop meaning, the last one will win as the previous order. What you need to do is to actually discontinue each of these orders first meaning each will have its own discontinuation order. It also implies that if you have multiple matches, you will need to use getOrderHistoryByConcept so that the most recent active one is what actually becomes the previousOrder for this discontinuation order