简体   繁体   中英

Yii2 understanding dataProvider

There are 2 statuses ORDER_PAID and ORDER_DELIVERED and i need to display 5 blocks on the page with following datasets:

  1. Total sum of orders: Each item in database has field sum, that I need to count.

  2. Sum of orders with status ORDER_PAID

  3. Sum of orders with status ORDER_DELIVERED
  4. A graph that displays the correlation between orders with ORDER_PAID and ORDER_DELIVERED statuses
  5. Table that contains only orders with ORDER_PAID status.

All the above depends on data that is selected by user (between to dates, last week, last month). There are also 4 request

getOrderDeliveredSum() + getOrderPaidSum() = getTotal()

For example I have function that :

function getOrderPaidSum(){
         return Orders::find()
                ->where(["owned" => \Yii::$app->user->id])
                ->andWhere(["status.code" => "ORDER_PAID"])
                ->sum();
    }

And also getOrdersContext that fetchs data for graph\\table:

function getOrdersContext($params){

    $query = Orders::find()
        ->where(["owned" => \Yii::$app->user->id])
        ->orderBy('id DESC');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    if(!($this->load($params) && $this->validate())){
        return $dataProvider;
    }

    $query->andFilterWhere([]);
    return $dataProvider;
}

But as you can see there are request that fetches the same data but for different purpose. Is there any optimization opportunities?

UPD 1 I want to get next values from my db:

  1. The total sum of orders for current user.
  2. To get the total sum of orders for current user I have to calculate order's sums with statuses ORDER_PAID and ORDER_DELIVERED
  3. I also use Highcharts::widget and GridView::widget to display the data. (It's a sortable table that contains orders with status ORDER_PAID and a graph that displays price for each order with ORDER_DELIVERED and ORDER_PAID .

a simple way is calculate the two sum you need separately

myTotalPaid  = Orders::find()
            ->where(["owned" => \Yii::$app->user->id])
            ->andWhere(["status.code" => "ORDER_PAID"])
            ->sum('my_column_for_sum');


myTotalDelivered  = Orders::find()
            ->where(["owned" => \Yii::$app->user->id])
            ->andWhere(["status.code" => "ORDER_DELIVERED"])
            ->sum('my_column_for_sum');    

then obtain the data Provider for ORDER_PAID

$query = Orders::find()
            ->where(["owned" => \Yii::$app->user->id])
            ->andWhere(["status.code" => "ORDER_PAID"])
            ->orderBy('id DESC');

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM