Search code examples
databasezend-frameworkzend-db

how to get Row object in ZF using adapter for query?


Is it possible to get Zend_Db_Table_Row object, with using db adapter for fetching instead of Zend_Db_Table?

For example, I have a next method

public function isAllowed($ip = null)
{

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

    var_dump($check);
}

if I work with Zend_Db_Table I'll get Zend_Db_Table_Row object here, but I have to work with db adapter object (because of using master-slave replication), so I have something like this

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

and here I get an array, how can I get Zend_Db_Table_Row here too?

Thanks.


Solution

  • You can instantiate a Row object directly with new and pass to the constructor an array of data to fill into it. You can get that data from a custom query you ran with the Adapter class.

    But you also need to pass a reference to a table, so the row knows if the keys of your array correspond to columns of the given table.

    See my answer in Zend_Db_Table_Row: Why do I have to use createRow()?

    Another solution is to use the Table class to fetch your row, but specify the db adapter:

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