Yii2尝试使用listView关系模型获取非对象错误的属性

问题描述 投票:-1回答:2

我有两张桌子。

  1. 学生(ID,电子邮件,密码,f_name,l_name,UNIQUE_ID,CREATE_DATE,LAST_UPDATE)
  2. 评论(ID,ad_id,commented_user,评论,CREATE_DATE,LAST_UPDATE)

表关系 - > comments.commented_user = students.email

评论课

    class Comments extends \yii\db\ActiveRecord
{

    //public $commented_user_fName;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'comments';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['comment'], 'string'],
            [['create_date', 'last_update'], 'safe'],
            [['ad_id', 'commented_user'], 'string', 'max' => 64],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'ad_id' => 'Ad ID',
            'commented_user' => 'Commented User',
            'comment' => 'Comment',
            'create_date' => 'Create Date',
            'last_update' => 'Last Update',
        ];
    }

    public function beforeSave($insert) {
        if ($this->isNewRecord){
            $this->commented_user = $_SESSION['login_student_email'];
            $this->create_date = new Expression('NOW()');
        }


        return parent::beforeSave($insert);
    }

    public function getStudentName(){
        $this->hasOne(Students::className() ,['commented_user' => 'email']);
    }

}

我的评论控制器索引方法

public function actionIndex($id)
    {
        $model = new Comments();
        $model->setAttribute('ad_id',$id);
        $searchModel = new CommentsSearch();
        $dataProvider = $searchModel->search(["CommentsSearch"=>['ad_id'=>$id]]);

        return $this->renderAjax('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'model' => $model,
        ]);
    }

我尝试在ListView中获取学生表的f_name

<?=
            ListView::widget([
                'dataProvider' => $dataProvider,
                'layout' => "{items}",
                'itemView' => 'view',
            ]);
            ?>

项目视图文件代码如下

<a href="#"><?= $model->studentName->f_name ?></a>

我收到了这个错误

PHP注意 - yii \ base \ ErrorException试图获取非对象的属性

在这条线上<a href="#"><?= $model->studentName->f_name ?></a>

我的代码有什么问题。请帮我

php mysql yii2 yii2-model
2个回答
0
投票

.是连接运算符,所以$model->studentName.f_name不被视为$model->{studentName.f_name}而是{$model->studentName} . f_name

你可能需要使用$model->studentName->f_name


0
投票

您应该像使用任何其他模型一样以$ model-> studentName-> f_name的身份访问该属性

© www.soinside.com 2019 - 2024. All rights reserved.