Multiple levels of relational data

Hi guys,

I just started to work with relational data in Yii2. I don’t understand all of it perfectly so I came here to ask.

I have several tables related to each other and sometimes a second relation works sometimes it doesn’t.

For example, I have an Employees table and a Departments table that are related through department_ID. Also I have a third table, call it Work for the example.

In Work my relation looks:




public function getEmployee()

    {

        return $this->hasOne(Employees::className(), ['employee_ID' => 'employee_ID']);

    }



In Employees the relation looks:




public function getDepartment()

    {

        return $this->hasOne(Department::className(), ['unique_ID' => 'department_ID']);

    }



I have this code in my WorkController:




$employee = $model->getEmployee()->select(['position', 'department_ID', 'collar']);

department = $employee->department



$employee->department gives the following error:

Getting unknown property: yii\db\ActiveQuery::department

Can you guys help me for a solution for this multi level relation?

In other tables I could go deeper like Department->Division->Head of Division (all three are separate tables) with the same type of relations.

Thanks!


$employee = $model->getEmployee()->select(['position', 'department_ID', 'collar'])->one();



http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#accessing-relational-data

Oh, now it seems obvious. Thank you!