检查CakePHP 3中的实体是否为空


Check if entity is empty in CakePHP 3

我试图找出如果我的$appointment实体是空的或不是在CakePHP,但这不起作用:

$appointment = $this->Appointments->get($id);
if($appointment->isEmpty()) {
    throw new NotFoundException("invalid appointment");
}

错误:

错误:Call to undefined method实体模型应用' ' '任命:isEmpty ()

正确的做法是什么?文档说它适用于QueryResultSet,但我需要它用于上述代码。

看起来您正在尝试通过主键获取单个实体。如果是这种情况,您不应该验证是否找到了它,如果没有找到,则抛出自己的异常。从我在文档中看到的,框架会自动为你做这些。

如果get操作没有找到任何结果,将引发Cake'Datasource'Exception'RecordNotFoundException。您可以自己捕获这个异常,或者允许CakePHP将其转换为404错误。

您需要手动处理异常。遵循以下方法:

/* Mention this on top of your page */
use Cake'Datasource'Exception'RecordNotFoundException;
use Cake'Network'Exception'NotFoundException;
public function test()
{
    try {
        $appointment = $this->Appointments->get($id);
    } catch (RecordNotFoundException $e) {
        $appointment = [];
    } 
    if (!$appointment) {
        $this->Flash->error(__("Invalid appointment"));
        return $this->redirect($this->referer());
    }
}