0

假设我有一张桌子:

$someTable = new Zend_Db_Table ('sometable');

我知道我可以使用表的文字名称构建查询。

$sel = $someTable -> select () 
                  -> from ('sometable', array ('col_foo', 'col_bar')) 
                  -> where ('some_condition')

并且我可以为表格设置别名。

$sel = $someTable -> select () 
                  -> from (array ('alias' => 'sometable'), array ('col_foo', 'col_bar')) 
                  -> where ('some_condition')

我也知道我可以在 from() 调用中直接使用 Zend_Db_Table :

$sel = $someTable -> select () 
                  -> from ($someTable, array ('col_foo', 'col_bar')) 
                  -> where ('some_condition')

但是当我尝试像下面那样对表对象进行别名时,我得到了一个致命错误。

$sel = $someTable -> select () 
                  -> from (array ('alias' => $someTable), array ('col_foo', 'col_bar')) 
                  -> where ('some_condition')

可捕获的致命错误: Zend_Db_Table 类的对象无法在...中转换为字符串

在我看来,这是有问题的行为,因为 from()、join() 等方法可以处理将 Zend_Db_Table 对象传递给它们,但当您想给它起别名时却不行!

上面的例子有点做作和简化来说明问题。真正的代码是在表之间进行连接,但是随着表对象的传入,我提前不知道它们的名称是什么。当然,我可以使用 info() 来解决上述问题,以获取表名并将它们作为字符串注入,但这意味着额外的代码对我来说看起来很乱。此外,这是 Zend_Db 在没有这种变通方法的情况下应该能够应对的情况。

我正在使用 Zend Framework 1.7.6。并继承 Zend_Db_Table_Abstract 来制作我的表对象。不幸的是,我无权安装 Zend 的升级版本。

4

1 回答 1

2

ZF 的升级版本无济于事,但您应该争论当前版本的 ZF 和 PHP 的安全角度(尝试永远不会有坏处;)):

$sel = $someTable -> select () 
                  -> from (array ('alias' => $someTable), array ('col_foo', 'col_bar')) 
                  -> where ('some_condition')

alias 想要成为字符串而不是对象,并且$someTable当前是对象。我认为你想要一些事情,比如$someTable->getConfig()->name;应该做你想做的事。

摘自:Zend_Db_Table_Abstract_from()

/**
 * Adds a FROM table and optional columns to the query.
 *
 * The first parameter $name can be a simple string, in which case the
 * correlation name is generated automatically.  If you want to specify
 * the correlation name, the first parameter must be an associative
 * array in which the key is the correlation name, and the value is
 * the physical table name.  For example, array('alias' => 'table').
 * The correlation name is prepended to all columns fetched for this
 * table.
 */

第一个参数也可以是一个实例,Zend_Db_Select()但不能将对象与数组混合。

考虑一下,您可以编写一个简单的实体类,它允许您为任何表名构建 Zend_Db_Table 的实例。

class Application_Model_DbTable extends Zend_Db_Table_Abstract
{
    protected $_name;
    protected $_primary;

    public function __construct($name, $primary = 'id') {
        $this->_name = $name;
        $this->_primary = 'something_other_then_id';

    }

    //implement __set and __get if you want

}

这将允许您只传递表名和该表的主 ID。您仍然可以使用整个 Zend_Db_Table api 以及您设计的任何自定义方法。

祝你好运。

于 2012-11-14T11:06:55.163 回答