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){
...
}
Related videos on Youtube
![Jørgen](https://i.stack.imgur.com/DujhQ.jpg?s=256&g=1)
Comments
-
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();