陷入 Zend_Db_Tables

问题描述 投票:0回答:1

尝试与

Zend_Db_Tables
合作 任务是从 2 个或可能是 3 个表中检索数据并以 json 形式返回。

代码:

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

为每个地方的每张桌子生成选择对我来说似乎是床解决方案。在这种情况下,我该如何生成

findParentRow

的选择
php json zend-framework zend-db-table
1个回答
0
投票

听起来您需要一种方法来指定要从父表中选择哪些字段,而不必编写整个

$select
。 这将需要一个自定义行类。 ZF 提供了一种简单的方法来做到这一点。 在您的依赖表类中,添加如下
rowClass
行:

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

然后像这样创建自定义类,它重写

findParentRow
方法以允许您输入简单的字段名称数组:

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', ...));
© www.soinside.com 2019 - 2024. All rights reserved.