2016-04-20 47 views
0

相關的模型在我訪問相關模型的財產像下面訪問一個NULL在yii2

$objPatientModel->physicianUser->diallingCode->phonecode 

解釋呢yii2觀點:

我有耐心表和病人表我的外鍵physician_user有撥號代碼(從另一個表的ID - 撥號代碼)和撥號代碼表我有屬性phonecode。

現在我的問題是,如果值爲physician_user是NULL,那麼這會引發錯誤,如'嘗試獲取非對象的屬性',這是因爲$ objPatientModel-> physicianUser返回NULL而不是空對象。我想知道是否有可以在yii2中覆蓋的任何類或方法,以避免發生上述錯誤而不進行檢查?

+0

您shoudn't重寫此邏輯返回空對象。但是如果你感興趣的話,這個邏輯通過PHP魔術方法'__get()'實現。 – SiZE

+0

@SiZE有什麼辦法讓我不需要放置支票? – alwaysLearn

+1

不是。你可以'嘗試...捕捉'異常或者放置像'($ objPatientModel-> physicianUser!== null?$ objPatientModel-> physicianUser-> diallingCode!== null?$ objPatientModel-> physicianUser-> diallingCode-> phonecode ...' – SiZE

回答

0

使用ArrayHelper。

\yii\helpers\ArrayHelper::getValue($objPatientModel, 'physicianUser.diallingCode.phonecode', null); 

它返回NULL physician_user的情況下,值爲NULL

ArrayHelper api