Trying to get property of non-object in yii2

試著忘記壹切 提交于 2020-05-27 06:16:09

问题


I want access to hasMany relation but i get error with this content

PHP Notice – yii\base\ErrorException

Trying to get property of non-object

this is my view : 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; ?>

and this is my frontend\models\News relations

  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']);
}

and this is NewsController

    <?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'));
    }

}

and this is 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) {
    }
  }
}

i can access to $model->cat->name but i can't access to $model->photos->id why?!


回答1:


The problem you're having is that $model->photos is an array. This is because you set the relationship with hasMany() implying that each News could have multiple Photos.

You can either do the following in your view:

<img class="img-responsive" src="photos/<?=$model->photos[0]->id?>.jpg" alt="">

This will display the first photo (provided there is one, if there's a change there are none then you would have to check that 0 is set).

Or you can display all photos with:

foreach($model->photos as $photo)
{ 
   echo '<img class="img-responsive" src="photos/'.$photo->id.'.jpg" alt="">';
}

(or any other design you want)




回答2:


You can access because it has a hasMany relation and $model->photos is an ActiveQuery, so you're be able to get with $model->photos->one()->id for the first one or make a loop with $model->photos->all()

More info: http://www.yiiframework.com/doc-2.0/yii-db-activequery.html




回答3:


You can always check first fetch later this way you will add a minor delay but you will surpress the message and check the output i.e.

    if ($model->photos)
    { return $model->photos->id;}
    else 
    {return NULL;} //or whatever you want
// or in your case 
    <div class="col-md-2">
        <a href="#">
    <?php (if $model->photos) 
        { 
   echo   
    '<img class="img-responsive" src="photos/'.$model->photos->id'.jpg"alt="">';
     } 
    else 
    {   
     echo   
    '<img class="img-responsive" src="photos/my-default_photo_for_no_photo.jpg" alt=""'; //or whatever else 
     }
    ?>
    </a>
        </div>


来源:https://stackoverflow.com/questions/33367392/trying-to-get-property-of-non-object-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!