Zend framework 使用zend db从表中获取行

Zend framework 使用zend db从表中获取行,zend-framework,zend-db,zend-db-table,Zend Framework,Zend Db,Zend Db Table,我基本上有下表 类别 id name categories_id_categories 1 Clothes null 2 Shirts 1 3 Pants 1 4 Electronics null 5 Tv 4 该表存储类别和子类别,如果类别_id _categories为空,则它们是主类别,否则它们是具有该id的类别的子类别。我想在页面上显示此内容,因此我在我的类别模型上创建了以下函数: publ

我基本上有下表

类别

id   name        categories_id_categories
1    Clothes     null
2    Shirts      1
3    Pants       1
4    Electronics null
5    Tv          4
该表存储类别和子类别,如果类别_id _categories为空,则它们是主类别,否则它们是具有该id的类别的子类别。我想在页面上显示此内容,因此我在我的类别模型上创建了以下函数:

public function getAllCategories()
{
    $select = $this->select()
                   ->where('categories_id_categories IS NULL');

    return $this->fetchAll($select);
}

public function getAllSubCategories()
{
    $select = $this->select()
                   ->where('categories_id_categories IS NOT NULL');

    return $this->fetchAll($select);
}
在我的控制器上:

    $categories = new Model_DbTable_Categories();

    $categoryList = $categories->getAllCategories();

    $categoriesAll = array();

    foreach ($categoryList->toArray() as $category) {
        $subCategories = $categories->getSubCategoriesByCategory($category['id']);
        $category['sub_categories'] = $subCategories->toArray();
        $categoriesAll[] = $category;
    }

    $this->view->categoryList = $categoriesAll;
categoryList是一个包含所有类别的数组,而关键子类别是另一个包含所有子类别的数组。这是可行的,但我想知道是否有一种方法可以使用对象而不是数组,或者只使用一个查询而不是2个查询

如果我从表中选择all,我会得到类别和子类别,但是我必须在视图中移动一些逻辑来选择我相信的子类别


提前谢谢

只需将$id放入getAllSubcategories并在模型中创建getSubCategories,如下所示:

public function geSubCategories($id = null) { $select = $this->select(); if ( $id == null ) { $select->where('categories_id_categories IS NOT NULL'); } else { $select->where('id = ?', $id); } return $this->fetchAll($select); } 公共函数geSubCategories($id=null) { $select=$this->select(); 如果($id==null){ $select->where('categories\u id\u categories不为NULL'); } 否则{ $select->where('id=?',$id); } 返回$this->fetchAll($select); }

$sql = "SELECT * FROM TABLE_NAME WHERE ID = 1";
$rows = $db->fetchAll($sql);

//One row return array
echo $rows[0]['field_name'];