首页 > 解决方案 > 如何访问 activeRecord 中模型的关系?

问题描述

我有一个像下面这样的模型:

 class Book extends ActiveRecord
   {
        { public function getDomain()
        {
            return $this->hasOne(Domain::className(), ['ID' => 'domainID']);
        }

        public function getOwnerPerson()
        {
            return $this->$this->hasOne(Person::className(), ['ID' => 'ownerPersonID']);
        }

        public function getCreatorUser()
        {
            return $this->$this->hasOne(User::className(), ['ID' => 'creatorUserID']);
        }

        public function getUpdaterUser()
        {
            return $this->$this->hasOne(User::className(), ['ID' => 'updaterUserID']);
        }
    }

我通过以下方式从 Book 模型创建了一个对象: $model=Book::find()->all(); 当我使用 时$model->domain,一切正常,但是当我使用时$model->ownerPerson,它会引发错误: Object of class backend\models\Book could not be converted to string

问题是什么?

标签: phpmodelyii2relation

解决方案


删除第二个 $this。

return $this->$this->hasOne(Person::className(), ['ID' => 'ownerPersonID']);
to
return $this->hasOne(Person::className(), ['ID' => 'ownerPersonID']);

推荐阅读