Tuesday, November 11, 2014

Active Relations from Yii 1.1 to Yii 2.0

In Yii 1.1.x relations were defined by an array within the model class. In Yii 2.0 that is no longer the case. Relations are now defined by getter methods within the model. For the complete specification see Working with Relational Data in the Yii 2.0 Guide.

So, if in Yii 1.1.x your relations looked something like this:
/**
 * @return array relational rules.
 */
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
      'address' => array(self::BELONGS_TO, 'Address', 'address_id'),
      'boxes'=>array(self::HAS_MANY,'Box', 'id'),
    );
}
While in Yii 2.0 You would build the relationships separately:
public function getAddress()
{
    return $this->belongsTo( Address::className(), 'address_id');
}

public function getBoxes()
{
    return $this->hasMany( Box::className(), 'id');
}
This also allows us to do some more fine tuning with the way the relationships are handled. Lets say that I want those Boxes ordered by their inventory number. The old way would have been:
public function relations()
{
    return array(
      'address' => array(self::BELONGS_TO, 'Address', 'address_id'),
      'boxes'=>array(self::HAS_MANY,'Box', 'id', 'order'=>'inventory_number'),
    );
}
The Yii 2.0 method would be:
public function getBoxes()
{
    return $this->hasMany( Box::className(), 'id')->orderBy('inventory_number');
}
Once you stop looking for the relations() method, it's easy to move on and get your models migrated to 2.0!