2011-07-08 22 views
0

試圖與Zend_Db_Tables 任務是從2或可能是3表中檢索數據並返回爲json。被困whith Zend_Db_Tables

代碼:

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); 
} 

問題是:

  1. 字段計數= 30中的每個(只需要3-10)
  2. 一些字段是BLOB/CLOB

爲每個地方的每張桌子生成選擇似乎對我來說是牀上解決方案。在這種情況下,我應該如何生成選擇​​

回答

0

聽起來就像你需要一種方法來指定你想從父表中選擇哪些字段,而不必寫整個$select。這將需要一個自定義的行類。採埃孚爲此提供了一種簡單的方法。在你的依賴表類,添加rowClass一行:

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

然後讓你的自定義類這樣的,它會覆蓋​​方法,讓你輸入字段名的簡單數組:

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); 
    } 

} 

如果Zend_Db_Table_Row_Abstract沒有指定第三個輸入必須是Zend_Db_Table_Select的實例,那麼會更容易,因爲那樣我們就可以自動檢查該輸入是否是列名稱的數組而不是該類的實例。所以我們添加我們自己的第四個輸入並將該邏輯放入方法中。現在你可以在你的控制器裏面做這樣的事情:

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

與我已經完成的相同的方式。 – Subdigger