1

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.

Vovkin
  • 436
  • 1
  • 5
  • 14

2 Answers2

2

DbAdapter is a lower-level interaction with the database compared to DbTable so you can't fetch a Table_Row directly (as Table_Row requires more data that is unknown to DbAdapter).

You can create a new Table_Row object after having fetched the results, however (this is taken and adapted from Zend_Db_Table_Abstract code):

$data = array(
    'table'   => $this->_dbTable,
    'data'     => $check,
    'readOnly' => false,
    'stored'  => true
);
$row = new Zend_Db_Table_Row($data);

See Zend/Db/Table/Abstract.php around like 1373.

Niko Efimov
  • 2,183
  • 3
  • 20
  • 30
2

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);
}
Community
  • 1
  • 1
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828