Yii2 ORDER BY for Relational Data in ActiveRecord

I have a request in my controller:

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

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

Is there a way to order "backups"?

I tried the following without results (or errors):

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

You can declare a sorted backups relation in the Object model using orderBy :

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

ends when these backups are output:

 foreach($model->sortedBackups as $backup){ ... } 
+7
source

All Articles