Relation models Yii1 vs Yii2


I have questions about code architecture between Yii1 and Yii2

in Yii 1 the model relation is like that

myModel extends CActiveRecord {

 public function relations() {

    return array(

      'relatedModel' => array(self::BELONGS_TO, 'RelatedModel', 'some_id'),




And use it like that




In Yii 2

myModel extends ActiveRecord {

  function getRelatedModel() {

     return $this->hasOne(RelatedModel::className(), ['some_id'=>'id'])



And use it like that




The advantages in Yii 1

according of getRelated method of CActiveRecord if we use $myModel->relatedModel more than of one time (for the same $myModel in the same php request) the relatedModel will not be loaded by sql query beacause is kept in the memory (by Yii 1 framework)

Now in Yii 2

if we user the $myModel->relatedModel many times Yii2 will runs the getRelatedModel() method using one() method

of ActiveQuery. In this way the same query will be executed many time in database reducing of performance

How to achieve this benefits of the Yii 1 in Yii 2 ?


From Accessing Relational Data

Bizley you are right!

I still learn the Yii2,

I was confused because I used $myModel->getRelatedModel()->one() by myself instead of $my_model->relatedModel that does all the job that is needed

The second one keep the relation internally in model for the next invokes without sql execution

Thanks with a vote :)

It’s one of the most magical parts of Yii 2.0 AR. We should probably revise it somehow to be more explicit.