简体   繁体   English

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

[英]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? 使用TableGateway,如何获取一行,空行,或者如果有多个行则抛出异常?

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. 然而,这似乎很乏味,我觉得我错过了Zend2的做法。 I'd hate to redo some pattern that tablegateway already uses. 我不想重做tablegateway已经使用的一些模式。

You can use the $rowSet->current() to fetch just one row. 您可以使用$rowSet->current()来获取一行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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