简体   繁体   English

zend get()单个记录返回异常而不是零结果

[英]zend get() single record returns exception instead of zero results

I have a very simple function in a zend skeleton that gets a row based on an ID you input. 我在zend骨架中有一个非常简单的函数,该函数根据您输入的ID获取一行。 If you use an ID that it finds in the database it works fine: 如果您使用在数据库中找到的ID,则可以正常工作:

$this->getTestimonialTable()->get($request->getPost('id'));

however if you put an id that doesn't exist, it returns an exception saying the row doesn't exist, which i know already. 但是,如果您放置了一个不存在的ID,它将返回一个异常,指出该行不存在,我已经知道了。

I want it so, if it finds the row, continue as normal, if not show that there was no results, not raise an exception. 我希望这样,如果找到行,则照常继续,如果不显示没有结果,请不要引发异常。

I've tried wrapping it in a count: 我尝试将其包装成一个计数:

 if (count($this->getTestimonialTable()->get($request->getPost('id'))) > 0) {
     //more than 1 result
 } else {
     //zero results
 }

however the exception is still raised on the initial call, i also tried wrapping it in a try statement: 但是在首次调用时仍然会引发异常,我也尝试将其包装在try语句中:

 try {
    $this->getTestimonialTable()->get($request->getPost('id'));
    //if im here i should have a result             
 } catch (Exception $e) {
     //zero results           
 }

Can anyone suggest what the problem is? 任何人都可以提出问题所在吗?


solved 解决了

So the principle was right, however i was running the code on the factory method, not running it on the database call. 所以原理是正确的,但是我在工厂方法上运行代码,而不是在数据库调用上运行代码。

so in my factory i now have 所以在我的工厂里

public function get($id)
 {
    $id  = (int) $id;
    $rowset = $this->tableGateway->select(array('id' => $id));
    $row = $rowset->current();

    if (!$row) {
        return null;
    }

    return $row;
 }

which then makes the above count work as intended 然后使上述计数按预期工作

if (count($this->getTestimonialTable()->get($request->getPost('id'))) > 0) {
 //more than 1 result
} else {
     //zero results
}

Zend is behaving as expected. Zend的行为符合预期。 You have asked it to return a row. 您已要求它返回一行。 It should do nothing more. 它应该什么也不做。 So, it's throwing an exception when it can't return a row. 因此,当它无法返回行时,它将引发异常。

I want it so, if it finds the row, continue as normal, if not show that there was no results, not raise an exception. 我希望这样,如果找到行,则照常继续,如果不显示没有结果,请不要引发异常。

Your best option is to put the database call in a try catch block, catch the exception and then parse the exception to determine if no rows were found. 最好的选择是将数据库调用放在try catch块中,捕获异常,然后解析异常以确定是否未找到行。

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

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