database - 如何使用适配器获取 ZF 中的 Row 对象进行查询?

标签 database zend-framework zend-db

是否可以使用数据库适配器代替 Zend_Db_Table 获取 Zend_Db_Table_Row 对象?

比如我有一个next方法

public function isAllowed($ip = null)
{

    $check = $this->_dbTable->fetchRow(
        $this->_dbTable->select()
                      ->from($this->_dbTable->getName(), array('id'))
                      ->where('ip = ?', $ip)
    );

    var_dump($check);
}

如果我使用 Zend_Db_Table 我会在这里得到 Zend_Db_Table_Row 对象,但是我必须使用 db 适配器对象(因为使用主从复制),所以我有这样的东西

public function isAllowed($ip = null)
{
    $db = My_Db_ConnectionManager::getConnection('slave');

    $check = $db->fetchRow($db->select()
                              ->from($this->_dbTable->getName(), array('id'))
                              ->where('ip = ?', $ip)
    );

    var_dump($check);
}

这里我得到一个数组,我怎样才能在这里也得到 Zend_Db_Table_Row?

谢谢。

最佳答案

您可以直接使用 new 实例化一个 Row 对象,并将一个数据数组传递给构造函数以填充它。您可以从使用 Adapter 类运行的自定义查询中获取该数据。

但您还需要传递对表的引用,以便行知道数组的键是否对应于给定表的列。

请参阅我在 Zend_Db_Table_Row: Why do I have to use createRow()? 中的回答

另一种解决方案是使用 Table 类来获取您的行,但指定数据库适配器:

public function isAllowed($ip = null)
{
    $slaveDb = My_Db_ConnectionManager::getConnection('slave');
    $masterDb = $this->_dbTable->getAdapter();
    $this->_dbTable->setOptions(array('db'=>$slaveDb));

    $check = $this->_dbTable->fetchRow(
        $this->_dbTable->select()
                      ->from($this->_dbTable->getName(), array('id'))
                      ->where('ip = ?', $ip)
    );

    $this->_dbTable->setOptions(array('db'=>$masterDb));

    var_dump($check);
}

关于database - 如何使用适配器获取 ZF 中的 Row 对象进行查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8576387/

相关文章:

php - 帮助理解 php 链接

mysql - 根据时间戳搜索相关行并添加行

php - Zend 框架 : How to give specific order to javascript files and scripts

php - zend-db 不执行 pdo 绑定(bind)替换

mysql - 查询 2 个表,其中一个字段链接到 2 个不同的值

php - Zend_Db_Table_Rowset 到对象数组

php - 尝试使用用户输入的值将自定义主键分配给数据库

database - 为什么树协议(protocol)没有死锁?

php - 选择选项中的 zend 表单自定义属性?

php - PHP YouTube API,获取上传状态