title: Laravel - get count in tree structure, where count in parent is sum of counts from children
body: <p>I'm struggling with this issue for some time, can't really find the solution, so I'm hoping for some help. </p>
  
  <p>I have two related models, <code>ModelOne</code> that is also related to itself and can have infinite number of children, grandchildren etc., and is related to <code>ModelTwo</code>.</p>
  
  <pre><code>class ModelOne extends Model
  {
      ...
  
      public function model_two()
      {
          return $this-&gt;hasMany(ModelTwo::class, 'foreign_key');
      }
  
      //recursively get all children, grandchildren etc.
      public function children() {
          return $this-&gt;hasMany(ModelOne::class, 'foreign_key')-&gt;with('children');
      }
  
      public function parent() {
          return $this-&gt;belongsTo(ModelOne::class, 'foreign_key');
      }
  }
  
  class ModelTwo extends Model
  {
      ...
  
      public function model_one()
      {
          return $this-&gt;belongsTo(ModelOne::class, 'foreign_key');
      }   
  }
  </code></pre>
  
  <p>In my get function from <code>ModelOne</code> I have:</p>
  
  <pre><code>public function get($id = null) {
      return is_null($id) ?
          ModelOne::withCount('model_two')-&gt;get() :
          ModelOne::withCount('model_two')-&gt;where('id', $id)-&gt;first();
  }
  </code></pre>
  
  <p>and that gives me nice one-dimensional array of objects (or one object), with count form related <code>ModelTwo</code>, which I need, but with individual count for every related object.</p>
  
  <p>The thing I need is, for every <code>ModelOne</code> object in return array who has children, grandchildren etc., to count in that object be the sum of counts from all its children, grandchildren etc. 
  So, for example, if I have one object of <code>ModelOne</code> with id=2, parent_id=1 and count of 3, and another object with id=3, parent_id=1 and count of 2, then for object with id=1, that is parent to previous two, count would be 5. This logic continues up in the tree for all nodes.</p>
  
  <pre><code>[
    {
      "id":1
      "parent_id":"NULL",
      "model_two_count":5
    },
    {
      "id":2
      "parent_id":1,
      "model_two_count":3
    },
    {
      "id":3
      "parent_id":1,
      "model_two_count":2
   }
  
   ...
  
  ]
  </code></pre>