0

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   
    }

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.