Answer the question
In order to leave comments, you need to log in
How to find out the sum of values for relationships in models?
there are models Goods
and Rating
they are connected like this
public function getRatings(){
return $this->hasMany(Rating::className(),['id_gods'=>'id']);
}
quantity
and the total number of records and how can i know this ?
Answer the question
In order to leave comments, you need to log in
in fact, you need to calculate aggregated fields. This issue is similarly described in the documentation, for example here
Haven't tested it, but it could be something like this:
$data = $model->getRatings()
->select('count(rating.*), SUM(rating.quantity)')
->alias('rating')
->createCommand()
->queryOne();
$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 questionAsk a Question
731 491 924 answers to any question