How to sum using YII2 hasMany relation?

I am using Yii2 and I have two tables:

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

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

 return $this->hasMany(\frontend\models\Points::className(), ['user_id' => 'id'])->sum('value'); 
+5
source share
2 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 can add this column to use this column in your sorts and filters.

+1
source

You can create your own dataProvider and use it in the GridView And Custom SearchModel.

0
source

Source: https://habr.com/ru/post/1233418/


All Articles