0
votes

I have one entity with one attribute called "total". Entity has relationships with itself. One to many relationship to child entities and one to one relationship to parent entity. Graph

One parent can has many children and every child can has its own children. Every parents total equals summary of its children totals. I need behavior, when changing childs total or deleting child affecting all parents totals to the root parent.

Example of parent-child tree

Is there any solution for that?

1
it sounds like what you want is for parents to do KVO on child objects, but that would require all objects to be 'live' in memory, aka allocated. Not a great solution. I think you'll need to do a more manual process, anytime a Entity X's 'total' is 'set' perform a manual core data query to find any parents where children contain Entity X and update their total, which will trigger a recursive pattern updating it's parents total value.Augie
Can‘t you simply refresh every parent going up, make that part of changing the tree.Fabian

1 Answers

0
votes

First, it is unclear what you mean by total. On the one had you said it is a property, and then you also said it is calculated based on the value of its children. What that implies to me is that there are really two different properties that you have. One is value which is usually (always?) zero for entities with children, and one that is total which is calculated property based on the sum of its own value plus the value of all of its children and their children etc. I suspect that this is the main idea that is tripping you up.

The second issue is efficiency for calculated the total which can be a long recursive process. First, don't try to preoptimize. If your graph is only a few deep, it is quite possible that calculating the value when needed is not a long process. If, and only if, you find that it is is talking to long and think that the best way is to have total precalcuated in the graph it should not be that hard.

  1. Have one place where nodes are inserted, removed or their values change. All changes in the application go to that one place.
  2. When a node is inserted go up the graph and add its value to all of its parents' total property
  3. When a node is removed go up the graph and remove its value from all of its parents' total property
  4. when a node's value is changed go up the graph and subtract the difference from the old value to the new value from all of its parents' total property