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