0

在此先感谢...请参阅下面的代码..我有 2 个型号、类别和产品

我的产品模型类 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 并将其显示在我的视图中......我可以拉出所有产品,但我不知道如何找到每个产品的父类别和绑定它们,有没有示例源代码?或任何建议?我需要一个包含所有产品和父类别名称的数组。请快点。谢谢

4

2 回答 2

0

完成此操作的最佳方法是迭代产品结果并创建包含所有类别 ID 的数组,然后使用 查询类别模型,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

无论如何,对于可能的错别字感到抱歉,在飞行中写了它;)

于 2012-02-20T21:27:17.917 回答
-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;
于 2012-02-20T21:36:53.873 回答