如何访问activeRecord中的模型关系?

时间:2019-01-10 12:41:06

标签: php model yii2 relation

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

 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

出什么问题了?

1 个答案:

答案 0 :(得分:1)

删除第二个$ this。

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