Dont undestood magic method

Hi im learning Yii 2, but i have a question because i do not undestood, in the next code from Yii from beginners.

The function getUser() retrive the information from the database using $this->hasOne

But my question is how in getUserName "$this->user->username;" can give me the username from the model User if in this code i do not indicate what is the ID for that user, i do not undestood this magic method

Warm Regards


namespace frontend\models;

use Yii;

use common\models\User;

class Perfil extends \yii\db\ActiveRecord


    public function attributeLabels()


        return [

            'id' => 'ID',

            'user_id' => 'User ID',

            'nombre' => 'Nombre',



    public function getUser()


        return $this->hasOne(User::className(), ['id' => 'user_id']);


    public function getUserName()


        return $this->user->username;




It’s explained here

When you call $this->user more or less this is called:

yii\db\BaseActiveRecord::__get() —> yii\base\Component::__get() —> frontend\models\Perfil::getUser() —> yii\db\BaseActiveRecord::hasOne() —> yii\db\ActiveRelationTrait::findFor()

The relation is established by using connection between two models (basically set in getUser()'s hasOne() options) (you can set the foreign key in database table as well) so when you call all this on Perfil object mapped for specific Perfil database row it knows it is related to User database row mapped in User object. And User object returns one of its attributes - username.

Hi Bizley, thanks a lot i undestood now very well.

Warm Regards