S
S
Sergey Beloventsev2016-10-15 22:02:43
Yii
Sergey Beloventsev, 2016-10-15 22:02:43

How to find out the sum of values ​​for relationships in models?

there are models Goodsand Ratingthey are connected like this

public function getRatings(){
            return $this->hasMany(Rating::className(),['id_gods'=>'id']);
        }

can i know the sum of the field quantityand the total number of records and how can i know this ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2016-10-17
@Sergalas

in fact, you need to calculate aggregated fields. This issue is similarly described in the documentation, for example here

A
Andrew, 2016-10-16
@mhthnz

Haven't tested it, but it could be something like this:

$data = $model->getRatings()
->select('count(rating.*), SUM(rating.quantity)')
->alias('rating')
->createCommand()
->queryOne();

Or just loop through the array:
$ratings = $model->ratings;
$count = $sum = 0;
if (is_array($ratings)) {
  $count = count($ratings);
  foreach($ratings as $rating) {
    $sum += (int) $rating->quantity;
  }
}
echo $count, $sum;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question