gridview - Yii2 DataPorivider $totalSum for a column -


i have order , ordersearch models.

in order list (actionindex) gridview there filtering , sorting. on of columns in order order_total (sum of products in order).

i need implement sum of order_total in gridview. if manually counting activedataprovider->getmodels() array_map spend 3 seconds 3000 orders (localhost). don't want miss time.

i see 2 ways make faster:

  1. create cache every filter , update lifetime (horrible)
  2. the interesting can right in ordersearch->search() method $query method. don't understand how can pass in controller.

example of code 2nd way:

class ordersearch extends order {      public $totalsum;       public function search($params)     {         $query = order::find();          $dataprovider = new activedataprovider([             'query' => $query,         ]);          $this->load($params);          $this->totalsum = $query->sum('order_total'); // works fast          return $dataprovider;     }  } 

after i'm trying property in controller:

public function actionindex() {     $searchmodel = new ordersearch();     $dataprovider = $searchmodel->search(yii::$app->request->queryparams);      $dataprovider->pagination->pagesize = 100;      // code below works slow , depends on pagination page size     // $orders = $dataprovider->getmodels();     // $totalsum = 1.0;     // array_map(function($item) use (&$totalsum) {     //     $totalsum += (float)$item->attributes['order_total'];     // }, $dataprovider->getmodels());      // here error     // unknown property – yii\base\unknownpropertyexception     // getting unknown property: yii\data\activedataprovider::totalsum     $totalsum = $dataprovider->totalsum;      return $this->render('index', [         'searchmodel' => $searchmodel,         'dataprovider' => $dataprovider,         'totalsum' => $totalsum,     ]); } 

how can set custom property dataprovider?

you wrote:

$dataprovider = $searchmodel->search(yii::$app->request->queryparams); 

so, $dataprovider return of method. and, can see here:

public function search($params) {     $dataprovider = new activedataprovider([         'query' => $query,     ]);      // code      return $dataprovider; } 

the method search returning activedataprovider. should, after using method, call attribute of original class:

$searchmodel = new ordersearch(); $dataprovider = $searchmodel->search(yii::$app->request->queryparams); // run search, have totalsum. $totalsum = $searchmodel->totalsum; 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -