简体   繁体   中英

Fetch only one row in Zend Framework 2 with TableGateway

Using the TableGateway, how can I fetch one row only , null rows, or throw an exception if there is more than one?

My code right now looks like

public function getFabricbyName($name){
    $select = new \Zend\Db\Sql\Select();
    $select->where->equalTo('name', $name);
    $result = $this->tableGateway->selectWith($select);

    if(count($result) > 1){
        throw new \Exception("More than one result returned when expecting only one item.");
    }
    return $result;
}

However, this seems tedious and I feel like I'm missing the Zend2-way of doing this. I'd hate to redo some pattern that tablegateway already uses.

You can use the $rowSet->current() to fetch just one row.

Also, you can use the table gateway instance to perform the select (no need to create a new instance)

I would make the method look like this.

public function getFabricbyName($name)
{
    $rowset  = $this->tableGateway->select(['name' => $name]);
    $current =  $rowset->current();

    if (! isset($current)) {

        throw new MyCustomNotFoundException(sprintf(
            'A fabric with name \'%s\' could not be found in \'%s\'',
            $name,
            __METHOD__
        ));
    }
    return $current;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM