在Yii框架中使用CPagination和createCommand函数

时间:2014-10-22 06:50:20

标签: php postgresql yii

我正在尝试使用CPagination。此处显示的示例http://www.yiiframework.com/doc/api/1.1/CPagination正在使用标准。我正在使用存储过程来选择数据。使用的数据库是postgresql。我正在使用create command function调用存储过程。

$command = Yii::app()->db->createCommand("select sp_images_select(:project_id,:milestone_id);");
$command->bindParam(":project_id",$this->project_id,PDO::PARAM_STR);
$command->bindParam(":milestone_id",$this->milestone_id,PDO::PARAM_STR);
$command->queryAll();

如何将CPagination与此命令的结果集一起使用。我正在使用ajax来显示图片库,如http://www.yiiframework.com/wiki/49/update-content-in-ajax-with-renderpartial/

所述

请帮忙。

提前致谢。

1 个答案:

答案 0 :(得分:0)

只有在您可以应用Limit(要检索的最大记录)时才能执行此操作 和Offset(从哪个记录开始)以某种方式存储过程。

让我们一步一步地完成示例并分析需要的内容

图片的Yii控制器

function actionIndex(){
    //Not needed, you apply criteria in your stored procedure with the 
    //arguments of your stored procedure.
    //$criteria=new CDbCriteria();

    // In some way you have to be able to determine how many records will 
    // be returned by the stored procedure when no limits are set 
    // (your challenge).
    $count= ..; // challenge here

    // create pagination object
    $pages=new CPagination($count);

    // Results per page, configure the maximum number of rows to be 
    // displayed (the limit).
    $pages->pageSize=10;

    // Set the page you are on. Either the starting page (0) or the page 
    // when the action is called by the linker (clicking on a button to 
    // go to a certanin page). The linker will send the page using get.
    // Pages are zero based so you have to decrease the received page by 
    // 1. 
    $pages->currentPage = (isset($_GET['page']) ? $_GET['page']-1 : 0)

    // You can not use this. This method applies the criteria to a plain 
    // vanilla query (not a stored procedure) and extends that query with 
    // a limit and offset.
    //$pages->applyLimit($criteria);
    // Instead, you retrieve the limit and offset from the pagination 
    // object and pass it to your stored procdure. F.i.
    $command->bindParam(":limit",$pages->limit,PDO::PARAM_INT);
    $command->bindParam(":offset",$pages->offset,PDO::PARAM_INT);

    // Get the the images with the stored procedure.
    $images=$command->queryAll();

    // Display the images using a view
    $this->render('index', array(
    'images' => $images,
         'pages' => $pages
    ));
}

因此,如果您想使用上述方法,这就是您必须要做的事情:

  • 查看您的存储过程是否支持LimitOffset
  • 如果是,请扩展存储的pocedure的参数以接收LimitOffset并应用
  • 找到一种方法来确定在未设置LimitOffset时存储过程将导致的记录数。这是必需的,因此分页对象可以根据当前页面计算Offset

希望这会让你走上正轨...