Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework: How to find a table row by the value of a specified column?

I am implementing my model exactly like the quickstart guide.

In my model I am trying to implement a findByToken() method. The current find() method accepts an $id parameter, but I want to find by the value of a different column.

//excerpt from the quickstart guide
public function find($id, Default_Model_Guestbook $guestbook)
{
    $result = $this->getDbTable()->find($id);
    if (0 == count($result)) {
        return;
    }
    $row = $result->current();
    $guestbook->setId($row->id)
              ->setEmail($row->email)
              ->setComment($row->comment)
              ->setCreated($row->created);
}

I tried doing something like this, but I don't think it worked:

$db = $this->getDbTable();
$where = $db->getAdapter()->quoteInto('token = ?', $token);
$result = $db->find($where);

What would be the proper way to find a row by the value of a specified column?

like image 540
Andrew Avatar asked Dec 18 '22 04:12

Andrew


2 Answers

$result = $db->fetchAll($where);

or if you are trying to retrieve only one row.

$result = $db->fetchRow($where);

You could also use the Zend_Db_Select Object, keeping the adapter a little further abstracted:

$db = $this->getDbTable();
$select = $db->select()->where('token = ?', $token);
$result = $db->fetchAll($select);
like image 128
Brian Fisher Avatar answered Mar 22 '23 23:03

Brian Fisher


This can be easily done by creating select object and fetching a row using this object. It's well described in manual: http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.execute

Your code could look like:

$select = $this->getDbTable()->select()->where('token = ?', (string) $token);
$row = $this->getDbTable()->fetchRow($select);
like image 25
Wojciech Szela Avatar answered Mar 23 '23 00:03

Wojciech Szela