2013-08-01 34 views
0

在类模型中,getAll方法用于返回所有类别数据。在下面的方法$ roots中的第一个活动记录具有所有根类别和$类别具有根类别的后代类别。如何添加这两个类别。以下是GETALL方法:添加两个模型类

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 
    } 

回答

2

两个问题在这里:

  1. 你只打算让category并在表中的最后根descendants因为foreach循环每次都会覆盖变量。为了防止这种情况,您需要制作$categoriy$categories阵列,并将其分配为$category[] = ...$categories[] = ...。或者,也许最好在循环结束时将它们合并到一个复合数组中。也许是这样的:

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

    你现在有存储为根类别所有根和派生类,那么它的后代,那么接下来的根类,数组,接着及其后代等

  2. $category是写的Category对象,而$categoriesdescendants()的数组。我希望这些也是Category对象。但是你不能连接一个对象和一个数组,你必须使用array_merge(),参见上面的示例。