2017-08-01 88 views
0

的意見/ search.php中Yii2 - 試圖與關係得到非對象的屬性

<?php foreach($dataProvider->getModels() as $call){ ?> 
<tbody> 
<tr> 
    <td><?=$call->created?></td> 
    <td><?=$call->call_datetime?></td> 
    <td><?=$call->call_from?></td> 
    <td><?=$call->call_to?></td> 
    <td><?=$call->duration?></td> 
    <td><?=$call->call_type?></td> 
    <td><?=$call->extension?></td> 
    <td><?=$call->callRecFiles->fname?></td> 
</tr> 
</tbody> 
<?php } ?> 

關係的模型/ Call.php

public function getCallRecFiles() 
{ 
    return $this->hasOne(CallRecording::className(), ['callref' => 'callref']); 
} 

控制器actionSearch

public function actionSearch($id) 
{ 
    $cust = new Customer(); 
    Yii::$app->user->identity->getId(); 
    $dataProvider = new ActiveDataProvider([ 
     'query' => Call::find() 
      ->with('customer', 'callRecFiles') // eager loading relations 'customer' & 'callRecFiles' 
      ->where(['custref' => $id]) 
      ->limit(10), 
     'pagination' => false, // defaults to true | when true '->limit()' is automatically handled 
    ]); 
    return $this->render('search',[ 
     'dataProvider' => $dataProvider, 
     'cust' => $cust, 
    ]); 
} 

我在這裏做錯了什麼或失蹤?我瀏覽過其他類似的問題,但似乎都涉及小部件或文件輸入。任何幫助表示讚賞。

+0

什麼是錯誤? –

+0

試圖獲取非物體的屬性 – Kyle

+0

在哪個模型 - >字段中出現此錯誤? – scaisEdge

回答

0

有兩個地方你可以有錯誤Trying to get property of non-object

首先是在這裏:

<td><?=$call->callRecFiles->fname?></td> 

爲了避免它,你應該使用if聲明:

<td><?= $call->callRecFiles ? $call->callRecFiles->fname : null ?></td> 

二是在這裏:

Yii::$app->user->identity->getId(); 

如果有在沒有訪問控制研究規則你的控制器,一個未登錄的用戶可以訪問這個動作和搜索方法,所以你沒有。用戶identity直到他登錄爲了避免它,你應該添加behaviors到控制器:

/** 
* @inheritdoc 
*/ 
public function behaviors() 
{ 
    return [ 
     'access' => [ 
      'class' => AccessControl::class, 
      'rules' => [ 
       [ 
        'allow'   => true, 
        'roles'   => ['@'], 
       ], 
      ], 
     ], 
    ]; 
} 

它會要求用戶在此控制器訪問你的行動之前登錄。

順便問一下,你是不是在使用這些代碼:

Yii::$app->user->identity->getId(); 

因此,移除它也是一個解決方案。

+0

謝謝@Yupik非常詳細的答案。我忘了把它放在問題中,但錯誤來自'​​ callRecFiles-> fname?>' – Kyle

相關問題