Yii2 ORDER BY for relational data in ActiveRecord

13,186

You can in Object model declare sorted relation backups with orderBy:

public function getSortedBackups()
  {

    return $this->hasMany(Backup::className(), ['object_id' => 'id'])->orderBy(['backups.updated_at'=>SORT_DESC]);
  }

end when you output these backups:

foreach($model->sortedBackups as $backup){
...
}
Share:
13,186

Related videos on Youtube

Jørgen
Author by

Jørgen

Mainly developing in Laravel and Yii2/CraftCMS.

Updated on July 28, 2022

Comments

  • Jørgen
    Jørgen almost 2 years

    I have a query in my controller:

    $model = Object::find()->where(['id' => $id])->with(['backups'])->one();
    

    getBackups is a hasMany() relation, so $model returns several 'backups'.

    Is there a way to order the 'backups'?

    I have tried the following without results (or errors):

     $model = Object::find()
              ->where(['id' => $id])
              ->with(['backups' => function($query) { 
                  $query->orderBy(['updated_at' => SORT_DESC]); 
              }])
              ->one();