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();
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){
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With