在 Yii 中的 gridview 查询后操作数据

Manipulating data after gridview query in Yii

我有一个 Gridview,其中包含来自 table 的数据,这通常没问题。 但在某些情况下我必须操纵数据,我不能只从查询中进行操作,因为有许多不同的情况并且需要复杂的计算。

示例: 从数据库加载的基础数据:

date        price   buy_price
2019-05-01  15.75   10
2019-05-02  20.15   10.50

经过复杂计算的相同数据

date        price   buy_price
2019-05-01  3.75   3
2019-05-02  4.70   3.10

我想使用 GridView,因为 ajax 过滤和排序非常有用。

在 Gridview 基于 DataProvider 执行查询后,我如何操作数据?

Yii2 Documentation about GridvViews 中的示例所述,您可以通过以下方式根据需要操作任何列:

echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
    ['class' => 'yii\grid\SerialColumn'],
    // Simple columns defined by the data contained in $dataProvider.
    'data',
    [
        'attribute' => 'price',
        'value' => function ($model) {
            return $model->getValue();  // Here you can manipulate the data as you wish.
        },
    ],
    [
        'attribute' => 'buy_price',
        'value' => function ($model) {
            return $model->buy_price * 2;  //Here you can manipulate the data as you wish.
        },
    ],
],]); 

处理数据后,您仍然可以使用排序或 ajax 过滤。