Search code examples
zend-frameworkzend-dbtable-relationships

how to grab data from multiple tables and display in view Using Zend Framework


Thanks in advance...see below the code.. i have 2 models, category and product

my product model class Admin_Model_Product extends 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
    )
);

}

my category model is:

class Admin_Model_Category extends Zend_Db_Table_Abstract {

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

} in my products controller i have

class Admin_ProductsController extends Zend_Controller_Action {

public function init() {

}

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

}

}

What i need to do is get all the products using fetchAll() method and need to get parentrow of each product and display it in my view... i can pull all the products but i dont know how to find each products parent category and bind them, is there any example source code? or any suggestion ? i need an array containg all products and parent category name ..please be quick.thanks


Solution

  • try the following :

    retrieve categories and their products :

    $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++;
    }
    

    then pass it to the view:

    $view->results = results;