Answer the question
In order to leave comments, you need to log in
How to work with sequentially linked tables in Yii2 using ActiveRecord?
Please help with Yii2 and ActiveRecord.
For several days I have been trying to figure out how to work with multiple sequentially linked tables using ActiveRecord in Yii2.
Tables:
department
id
value
building
id
value
department_id (foreign key)
room
id
value
building_id (foreign key)
Here is the working SQL code:
SELECT department.value, room.id, room.value
FROM department
LEFT JOIN building ON department.id=building.department_id
LEFT JOIN room ON building.id=room.building_id
WHERE department.id = 7
Answer the question
In order to leave comments, you need to log in
Use a Gii generator and it will do everything for you. Department
model .
class Department extends \yii\db\ActiveRecord {
/**
* @return \yii\db\ActiveQuery
*/
public function getBuildings() {
return $this->hasMany(Building::className(), ['department_id' => 'id']);
}
// ...
}
class Building extends \yii\db\ActiveRecord {
/**
* @return \yii\db\ActiveQuery
*/
public function getDepartment() {
return $this->hasOne(Department::className(), ['id' => 'department_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getRooms() {
return $this->hasMany(Room::className(), ['building_id' => 'id']);
}
// ...
}
var_dump($building->department);
var_dump($building->rooms);
class Room extends \yii\db\ActiveRecord {
/**
* @return \yii\db\ActiveQuery
*/
public function getBuilding() {
return $this->hasOne(Building::className(), ['id' => 'building_id']);
}
// ...
}
var_dump($room->building);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question