yii\db\Query::average PHP Méthode

average() public méthode

Returns the average of the specified column values.
public average ( string $q, Connection $db = null ) : mixed
$q string the column name or expression. Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
$db Connection the database connection used to generate the SQL statement. If this parameter is not given, the `db` application component will be used.
Résultat mixed the average of the specified column values.
    public function average($q, $db = null)
    {
        if ($this->emulateExecution) {
            return 0;
        }
        return $this->queryScalar("AVG({$q})", $db);
    }

Usage Example

 /**
  * Updates all Entries of a Contest with votecount and avg rating
  * 
  * @param \app\models\Contest $Contest Contest Object
  */
 private function UpdateContestEntries($Contest)
 {
     $Entries = Entry::findAll(['contest_id' => $Contest->id]);
     foreach ($Entries as $Entry) {
         $avgQuery = new Query();
         $avgQuery->from(Tweet::tableName())->where(['entry_id' => $Entry->id, 'needs_validation' => 0, 'old_vote' => 0]);
         $avgRating = $avgQuery->average('rating');
         $votestQuery = new Query();
         $votestQuery->from(Tweet::tableName())->where(['entry_id' => $Entry->id, 'needs_validation' => 0, 'old_vote' => 0]);
         $votes = $votestQuery->count();
         $Entry->votes = $votes;
         $Entry->avg_rating = round($avgRating, 2);
         $Entry->save();
     }
 }
All Usage Examples Of yii\db\Query::average