phpjsonzend-frameworkzend-db-table

stuck whith Zend_Db_Tables


trying to working with Zend_Db_Tables task is to retrive data from 2 or may be 3 tables and return as json.

code:

public function getWorkerAction()
{
    $request = $this->getRequest();

    $workers = new table_1();
    if (!$worker) {
        $res = array(
            'success' => false,
            'data' => 'empty',
        );
    }
    else {
        $card = $worker->findParentRow('Table2');
        $res = array(
            'success' => true,
            'data' => array_merge($worker->toArray(), $card->toArray()),
        );
    }

    $this->_helper->json($res);
}

problem is:

  1. field count = 30 in each (need only 3-10)
  2. some fields is BLOB/CLOB

generate select for every table in every place seems bed solution for me. and in this case how shall i generate selects for findParentRow


Solution

  • Sounds like you're needing a way to specify which fields you want to select from the parent table without having to write a whole $select. That will require a custom row class. ZF provides an easy way to do this. In your dependent table classes, add a rowClass line like this:

    class Table2 extends Zend_Db_Table_Abstract {
        ...
        protected $_rowClass = 'CustomTableRow';
        ...
    }
    

    Then make your custom class like this, which overrides the findParentRow method to allow you to input a simple array of field names:

    class CustomTableRow extends Zend_Db_Table_Row {
    
        public function findParentRow($parentTable, $ruleKey = null, Zend_Db_Table_Select $select = null, array $fields = array()) {
            if ($fields) {
                if ($select) {
                    $select->columns($fields);
                } else {
                    if (is_string($parentTable)) {
                        $parentTable = $this->_getTableFromString($parentTable);
                    } else if (!$parentTable instanceof Zend_Db_Table_Abstract) {
                        throw new Exception("Parent table parameter can only be a string or an instance of Zend_Db_Table_Abstract");
                    }
    
                    $select = $parentTable->select()
                        ->from($parentTable, $fields);
                }
            }
            return parent::findParentRow($parentTable, $ruleKey, $select);
        }
    
    }
    

    It would be easier if Zend_Db_Table_Row_Abstract didn't specify that the 3rd input has to be an instance of Zend_Db_Table_Select, because then we could automatically check whether that input is an array of column names instead of an instance to that class. So we add a 4th input of our own and put that logic inside the method. Now you can do something like this inside your controllers:

    $worker->findParentRow('Table2', null, null, array('field1', 'field2', ...));