A
A
Arock2015-07-19 14:32:01
MySQL
Arock, 2015-07-19 14:32:01

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

How to implement this with ActiveRecord?
PS
If you need to join one table, then everything is simple.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Belikov, 2015-07-19
@Arock

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']);
  }
  // ...
}

Can receive:
Model Building .
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']);
  }
  // ...
}

May receive:
var_dump($building->department);
var_dump($building->rooms);

Room model .
class Room extends \yii\db\ActiveRecord {
  /**
   * @return \yii\db\ActiveQuery
   */
  public function getBuilding() {
    return $this->hasOne(Building::className(), ['id' => 'building_id']);
  }
  // ...
}

May receive:
var_dump($room->building);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question