我想访问 hasMany 关系,但我收到此内容错误
PHP 通知 – yii\base\ErrorException
试图获取非对象的属性
这是我的观点:news/index.php
<?php foreach($models as $model): ?>
<!-- Project One -->
<div class="row">
<div class="col-md-2">
<a href="#">
<img class="img-responsive" src="photos/<?=$model->photos->id?>.jpg" alt="">
</a>
</div>
<div class="col-md-10">
<h4>
<div class="row">
<div class="col-sm-8">
دسته بندی:<?= $model->cat->name; ?>
</div>
<div class="col-sm-4">
تاریخ:
</div>
</div>
</h4>
<h3><?=$model->title ?></h3>
<p><?=$model->body ?></p>
<a class="btn btn-primary" href="#">View Project <span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
<hr>
<!-- /.row -->
<?php endforeach; ?>
这是我的前端\模型\新闻关系
public function getCat()
{
return $this->hasOne(Categories::className(), ['id' => 'cat_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPhotos()
{
return $this->hasMany(Photos::className(), ['news_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getViews()
{
return $this->hasMany(Views::className(), ['news_id' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getVotes()
{
return $this->hasMany(Votes::className(), ['news_id' => 'id']);
}
这是新闻控制器
<?php
namespace frontend\controllers;
use frontend\models\News;
class NewsController extends \yii\web\Controller
{
public function actionIndex()
{
$models =News::find()->all();
return $this->render('index',compact('models'));
}
}
这是vardump($model->photos)
array(1) {
[0]=>
object(frontend\models\Photos)#84 (8) {
["_attributes":"yii\db\BaseActiveRecord":private]=>
array(2) {
["id"]=>
int(2)
["news_id"]=>
int(2)
}
["_oldAttributes":"yii\db\BaseActiveRecord":private]=>
array(2) {
["id"]=>
int(2)
["news_id"]=>
int(2)
}
["_related":"yii\db\BaseActiveRecord":private]=>
array(0) {
}
["_errors":"yii\base\Model":private]=>
NULL
["_validators":"yii\base\Model":private]=>
NULL
["_scenario":"yii\base\Model":private]=>
string(7) "default"
["_events":"yii\base\Component":private]=>
array(0) {
}
["_behaviors":"yii\base\Component":private]=>
array(0) {
}
}
}
我可以访问$model->cat->name
但我无法访问$model->photos->id
为什么?!