如何从多个表中获取数据并在视图中显示使用Zend Framework

时间:2012-02-20 21:23:22

标签: zend-framework zend-db table-relationships

提前致谢...请参阅下面的代码..我有2个型号,类别和产品

我的产品型号     class Admin_Model_Product扩展Zend_Db_Table_Abstract {

protected $_name = 'products';
protected $_referenceMap = array(
    'category' => array(
        'columns' => array('category_id'),
        'refTableClass' => 'Admin_Model_Category',
        'refColumns' => array('id'),
        'onDelete' => self::CASCADE,
        'onUpdate' => self::RESTRICT
    )
);

}

我的类别模型是:

class Admin_Model_Category extends Zend_Db_Table_Abstract {

protected $_name = 'categories';
protected $_dependentTables = array('Admin_Model_Product');

} 在我的产品控制器中我有

class Admin_ProductsController extends Zend_Controller_Action {

public function init() {

}

public function indexAction() {
    echo '<pre>';
    $model = new Admin_Model_Product();

}

}

我需要做的是使用fetchAll()方法获取所有产品,并且需要获得每个产品的parentrow并在我的视图中显示...我可以提取所有产品但我不知道如何找到每个产品父类和绑定它们,是否有任何示例源代码?或任何建议?我需要一个包含所有产品和父类别名称的数组。请快速。谢谢

2 个答案:

答案 0 :(得分:0)

实现此目的的最佳方法是迭代产品结果并创建包含所有categories_ids的数组,然后使用where('category_id IN (?)', $array_of_categories_ids)查询类别模型,然后使用id_category => row_pairs从类别行集创建数组。然后你可以在两个查询中执行此操作:)

$categories_ids = array();
foreach ($products as $product)
{
     $categories_ids[ $product->category_id ] = $product->category_id; // set key to category id to avoid duplicated category' ids
}
$categories = $categoryModel->fetchAll($categoryModel->select()->where('id_category in (?)', $categories_ids)); // here u have to add check on array 'coz if empty it will thoro Query exception
// now just iterate over categories
$categories = array();
foreach ($categories as $category)
{
     $categories[ $category->id_category ] = $category;
}
// now when iterating over products u can just do $categories[ $product->category_id ] to get proper category for profuct

无论如何,对于可能的拼写错误,请在飞行中写下来;)

答案 1 :(得分:-1)

尝试以下方法:

检索类别及其产品:

$model_category = new Admin_Model_Category();
$categorySet = $model_category->fetchAll(); 
$categories = $categorySet->toArray();

$i = 0;
$results = array();
foreach($categories as $category)
   $categoryRow = $model_category->fetchRow('id =', $category->category_id)
   $products = $categoryRow->findDependentRowset('Admin_Model_Product');
   $results[$i]['parent'] = $category;
   $results[$i]['products'] = $products;
   $i++;
}

然后将其传递给视图:

$view->results = results;