使用 TableGateway 在 Zend Framework 2 中仅获取一行

Fetch only one row in Zend Framework 2 with TableGateway

使用 TableGateway,如何获取一行 ,空行,或者如果多于一行则抛出异常?

我的代码现在看起来像

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

但是,这看起来很乏味,而且我觉得我错过了 Zend2 的做法。我不想重做 tablegateway 已经使用的一些模式。

您可以使用 $rowSet->current() 只获取一行。

另外,您可以使用table网关实例来执行select(无需创建新实例)

我会让这个方法看起来像这样。

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