0

我正在尝试在 Yii 框架上创建小型应用程序,但一时无法理解。我有从 CActiveRecord 扩展的 Order 模型,在索引操作中我尝试使用 Order 模型两次但遇到了一些麻烦。

原因是在表格和最后一行中显示分页记录我希望显示某些字段的平均总数,并且必须为按排序/过滤条件过滤的所有记录计算此总数

这是行动代码:

public function actionIndex()
{
    $model = new Order('search');
    $model->unsetAttributes();
    if (isset($_GET['Order']))
        $model->attributes = $_GET['Order'];

    // Get average totals by current filters
    $totals = array();
    $tm = clone $model;
    $tmdp = $tm->search();
    $tmdp->criteria->select = array('avg(price) as avgPrice', 'avg(cost) as avgCost');
    $data = $tmdp->getData(true);
    $totals['cost'] = number_format($data[0]->avgCost, 0, '.', ' ');
    $totals['price'] = number_format($data[0]->avgPrice, 0, '.', ' ');
    $totals['marja'] = Order::getMarjaVal(round($data[0]->avgCost, 0), round($data[0]->avgPrice, 0));

    $this->render('index', array(
        'model'         => $model,
        'totals'        => $totals
    ));
}

在我看来,我以相同的方式获取数据$data = $model->search()->getData();

因此,如果我查看第一页 - 一切正常,但如果我更改页面,则$data = $tmdp->getData(true); 得到空数组。我还尝试为$tmdp设置页面,例如:

    $tmdp->criteria->select = array('avg(price) as avgPrice', 'avg(cost) as avgCost');
    $tmdp->pagination->setCurrentPage(0);
    $data = $tmdp->getData(true);

但在此之后,我只从第一页获取数据。

请有人能告诉我如何正确地做到这一点???

4

1 回答 1

0

当我们在分页中更改当前页面时,Yii 会自动更新 $_GET['Order_page'] 值(如果未设置此值 - 它将创建它),并且当我们从数据提供者获取数据时分页会自动获取此值。所以对于这段代码,我做了这样的改变:

public function actionIndex()
{
    $model = new Order('search');
    $model->unsetAttributes();
    if (isset($_GET['Order']))
        $model->attributes = $_GET['Order'];

    // Get average totals by current filters
    $totals = array();

    $tm = clone $model;
    $tdp = $tm->search();
    $tdp->criteria->select = array('avg(price) as avgPrice', 'avg(cost) as avgCost');
    if (isset($_GET['Order_page'])) {
        $curPage = $_GET['Order_page'] - 1;
    } else {
        $curPage = 0;
    }
    $tdp->pagination->currentPage = 0;
    $data = $tdp->getData(true);
    $totals['cost'] = number_format($data[0]->avgCost, 0, '.', ' ');
    $totals['price'] = number_format($data[0]->avgPrice, 0, '.', ' ');
    $totals['marja'] = Order::getMarjaVal(round($data[0]->avgCost, 0), round($data[0]->avgPrice, 0));
    $tdp->pagination->currentPage = $curPage;

    $this->render('index', array(
        'model'         => $model,
        'totals'        => $totals
    ));
}

所以我们试图从 $_GET 全局数组中获取页面,在 owr 操作之后我们只是更新这个值

于 2012-08-01T16:59:46.220 回答