2016-10-07 24 views
0

我試圖找出如果我的$任命實體爲空或不在CakePHP的空白,但這並不工作:檢查的實體是一個在CakePHP 3

$appointment = $this->Appointments->get($id); 

if($appointment->isEmpty()) { 
    throw new NotFoundException("invalid appointment"); 
} 

錯誤:

Error: Call to undefined method App\Model\Entity\Appointment::isEmpty()

這樣做的正確方法是什麼? docs說它適用於QueryResultSet,但我需要它提供的代碼。

回答

0

您需要手動處理異常。按照這種方法:

/* 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()); 
    } 
} 
4

它看起來像你試圖Get a Single Entity by Primary Key。如果是這樣的話,你不應該驗證它是否被發現並且拋出了你自己的異常。從我在文檔中看到的,框架會自動爲您做。

If the get operation does not find any results a Cake\Datasource\Exception\RecordNotFoundException will be raised. You can either catch this exception yourself, or allow CakePHP to convert it into a 404 error.

+0

或者只是使用find()來代替,如果可以通過設計阻止這種錯誤,請不要嘗試捕獲該錯誤。 – mark

相關問題