我基本上有以下表格,
分类
id name categories_id_categories
1 Clothes null
2 Shirts 1
3 Pants 1
4 Electronics null
5 Tv 4
该表存储类别和子类别,如果categories_id_categories为null,则它们是主要类别,否则它们是具有该ID的类别的子类别。我想在页面上显示这个,所以我在我的Categories模型上创建了这个函数:
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是一个包含所有类别的数组,关键的sub_categories是另一个包含所有子类别的数组。这有效,但我想知道是否有办法使用对象而不是数组,并且可能只使用一个查询而不是2?
如果我从表格中选择所有内容,我会得到类别和子类别,但是我必须将一些逻辑移到视图中以选择我认为的子类别。
提前致谢!
答案 0 :(得分:2)
只需将$ 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); }
答案 1 :(得分:0)
$sql = "SELECT * FROM TABLE_NAME WHERE ID = 1";
$rows = $db->fetchAll($sql);
//One row return array
echo $rows[0]['field_name'];
http://framework.zend.com/manual/1.12/en/zend.db.table.row.html
http://framework.zend.com/manual/1.12/en/zend.db.table.rowset.html