2016-03-03 66 views
0

我正在使用ajax從返回字符串數據的服務器調用方法。但是,我收到以下錯誤。如何從YII2中的關係中檢索列

PHP的通知「警予\基地\ ErrorException」有消息「試圖讓非對象的 財產」

可能這條線$first_day=$row->tblStaff2->first_day_service;給出了錯誤。

public function actionGet_loyalty() { 
     $model = \common\models\staffs\TblStaff::find()->joinWith('tblStaff2')->all(); 
     $string = "<table class='table table-striped'><tr><th>Name</th><th>Number of Years</th></tr>"; 
     foreach ($model as $row) { 
      $first_day=$row->tblStaff2->first_day_service; 
      $midname = ucwords($row->midname); 
      $name = ucwords($row->firstname) . " " . $midname[0] . ". " . ucwords($row->lastname); 
      $string.="<tr>" 
        . "<td>" . $name . "</td>" 
        . "<td>" . $first_day . "</td>" 
        . "</tr>"; 
     } 
     $string.="</table>"; 
     return $string; 
    } 

TblStaff關係

public function getTblStaff2() { 
    return $this->hasOne(TblStaff2::className(), ['staff_id' => 'id']); 
} 

回答

0

我已經修改了你的代碼。找到它下面

public function actionGet_loyalty() { 

    $model = \common\models\staffs\TblStaff::find()->all(); 
    $string = "<table class='table table-striped'><tr><th>Name</th><th>Number of Years</th></tr>"; 
    foreach ($model as $row) { 

     //What I added 
     foreach($row->tblStaff2 as $value){ 
      $first_day = $value->first_day_service; 
     //Here is where it stopped 

     $midname = ucwords($row->midname); 
     $name = ucwords($row->firstname) . " " . $midname[0] . ". " . ucwords($row->lastname); 
     $string.="<tr>" 
       . "<td>" . $name . "</td>" 
       . "<td>" . $first_day . "</td>" 
       . "</tr>"; 
     } 
    } 
    $string.="</table>"; 
    return $string; 
} 

你可以刪除我添加到它的評論,當你得到它的工作。

+0

這仍然給出相同的錯誤。我認爲沒有必要另闢蹊徑,因爲它是一對一的關係。 – beginner

相關問題