19

Trying to fetch a description from my database. The query returns the result but I would like to order the result to only show the one with the highest vote.

The vote should be calculated by the upvoted column subtracted by the downvoted column

$description = UnitDescription::find()
   ->where(['id_unit' => $model->id])
   ->orderBy([
      'upvoted - downvoted' => SORT_DESC //Need this line to be fixed
   ])
   ->one();

I was hoping someone might have a way to write this part of the query - Thanks

Jonnny
  • 4,939
  • 11
  • 63
  • 93
william
  • 529
  • 2
  • 5
  • 14

1 Answers1

34

You should simply try :

$description = UnitDescription::find()
    ->where(['id_unit' => $model->id])
    ->orderBy(['(upvoted - downvoted)' => SORT_DESC])
    ->one();
soju
  • 25,111
  • 3
  • 68
  • 70