2017-08-01 105 views
1

我使用Yii2開發項目中的DataTables插件,在網格中顯示用戶信息的一些字段。如何處理Yii2查找方法中無記錄的錯誤?

我有這樣的代碼來獲取每個用戶的最後訪問:

$lastDate = SeenLog::find()->where(['user_id' => $this->id]) 
     ->orderBy(['id' => SORT_DESC]) 
     ->one()->visit_date; 

但我給出的這個錯誤:

DataTables warning: table id=w0 - Trying to get property of non-object and nothing shows in grid. 

現在看來,這是因爲有一些用戶在沒有記錄表。

我該如何處理這個錯誤?

謝謝。

回答

4

您需要先檢查是否已從數據庫中提取日誌。

$log = SeenLog::find()->where(['user_id' => $this->id]) 
     ->orderBy(['id' => SORT_DESC]) 
     ->one(); 
$lastDate = $log ? $log->visit_date : null; 
相關問題