Dorin Chiran
Dorin Chiran

Reputation: 11

Zend2 TableGateway: how to retrieve a set of data

I have a ContactsTable.php module and an function like this:

public function getContactsByLastName($last_name){
    $rowset = $this->tableGateway->select(array('last_name' => $last_name));
    $row = $rowset->current();
    if (!$row) {
        throw new \Exception("Could not find row record");
    }
    return $row;
}

which is ok, but it only returns one row. The problem is in my database I have multiple records with the same Last Name, so my question is: How can I return a set of data?

I tried this:

$where = new Where();  
$where->like('last_name', $last_name);
$resultSet = $this->tableGateway->select($where);
return $resultSet;

but it doesn't work.

Upvotes: 0

Views: 794

Answers (2)

Harish Singh
Harish Singh

Reputation: 3329

You can use the resultset to get array of rows:

public function getContactsByLastName($last_name) {
        $select = new Select();
        $select->from(array('u' => 'tbl_users'))
               ->where(array('u.last_name' => $last_name));

        $statement = $this->adapter->createStatement();
        $select->prepareStatement($this->adapter, $statement);
        $result = $statement->execute();

        $rows = array();
        if ($result->count()) {
            $rows = new ResultSet();
            return $rows->initialize($result)->toArray();
        }

        return $rows;
}

Its working for me.

Upvotes: 0

SzymonM
SzymonM

Reputation: 904

Your first function should work as you expect, just remove line

$row = $rowset->current();

So, complete function should look like this:

public function getContactsByLastName($last_name){
        $rowset = $this->tableGateway->select(array('last_name' => $last_name));

        foreach ($rowset as $row) {
            echo $row['id'] . PHP_EOL;
        }
}

More info you can find in documentation http://framework.zend.com/manual/2.2/en/modules/zend.db.table-gateway.html

Upvotes: 3

Related Questions