Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 ORDER BY for relational data in ActiveRecord

Tags:

yii2

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();
like image 305
Jørgen Avatar asked Apr 18 '15 22:04

Jørgen


1 Answers

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){
...
}
like image 111
user1852788 Avatar answered Nov 09 '22 05:11

user1852788