Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum using YII2 relation hasMany?

Tags:

mysql

yii2

I'm using Yii2 and I have two tables:

user (id)
answer_points (id, user_id, value)

How can I sum all the points of each user in a gridview with filtering, sorting by sum DESC and relation?

return $this->hasMany(\frontend\models\Points::className(), 
       ['user_id' => 'id'])->sum('value');
like image 927
Evaldas Avatar asked Nov 10 '22 03:11

Evaldas


1 Answers

In your User model, you should have this getter

public function getPoints()
{
    return $this->hasMany(\frontend\models\Points::className(), ['user_id' => 'id'])->sum('value');
}

In your UserSearch model, you can do

public function search(...) {
    $query = User::find()->joinWith('points'); //<--- alias to the getter defined above
    ...
}

Now you should be able to add that column to use that column in your sorts and filters.

like image 109
saada Avatar answered Nov 15 '22 05:11

saada