yii2virtual-attributeyii2-modelyii-relations

Yii2: How to order a relation by virtual attribute?


I have a class Group, which hasMany Teams and I would like to order them by their score. A team's score is calculated by iterating through its games, so score is not a db-field, it's a virtual read-only attribute.

This is my attempt:

public function getTeams()
{
    return $this->hasMany(Team::className(), ['group' => 'id'])->orderBy(['score' => SORT_ASC]);
}

This does not work, as score is not a db-field. How can I order a relation by a virtual attribute?


Solution

  • You can create a database view, e.g. team_score. The view should contain all the fields from the team table and a calculated field score (calculated with SQL commands). Then you can create a model TeamScore, which you can quite easily order by the field score.

    Disadvantage: The values will be by every calling the view new calculated, what requires more compute power, than when the calculated values are directly stored in the table.

    Advantage: It is simple to implement and firstly for displaying tables with many relations it saves a lot of coding.