Search code examples
phpyii

Adding two Model Class


In Category Model, getAll method is used for returning all category data. First Active Record in below method $roots have all roots category and $categories have roots category's descendants category. How to add these two Category. Following is getAll Method:

   public function getAll()
    {
      $roots = Category::model()->roots()->findAll();
      foreach($roots as $root)
      {
        $category = Category::model()->findByPk($root->root);   
        $categories = $category->descendants()->findAll();
      }
      return $category + $categories;  // this does not concatenate, causes error   
    }

Solution

  • Two problems here:

    1. You are only going to get the category and descendants of the last root in your table because the foreach loop will overwrite the variables each time. To prevent this, you will need to make $categoriy and $categories arrays, and assign like $category[] = ... and $categories[] = .... Or maybe better you could merge them into a composite array at the end of the loop. Maybe something like this:

      foreach($roots as $root)
        {
          $category = Category::model()->findByPk($root->root);   
          $categories[] = $category;
          $categories = array_merge($categories, $category->descendants()->findAll());
        }
      return $categories;
      

      You now have an array of all root and descendent categories stored as root category, then its descendents, then the next root category, then its descendents, etc.

    2. $category is a Category object as written, and $categories is an array of descendants(). I am hoping that these are Category objects as well. But you can't concatenate an object with an array, you have to use array_merge(), see my example above.