2017-08-01 20 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

相关问题