Yii 2分页不正常

时间:2014-12-29 08:38:13

标签: php pagination yii2

我正在尝试在我的Web应用程序中进行分页。但似乎并没有给我正确的totalCount属性数。我的代码是 -

    $find_query = "SELECT * FROM business WHERE status='Enabled' ";

    $query = Business::findBySql($find_query);

    //$query = Business::find()->where(['status' => 'Enabled']);

    $countQuery = clone $query;

    $pages = new Pagination(['totalCount' => $countQuery->count(), 'defaultPageSize' => 10]);

    $data_rows = $query->offset($pages->offset)
            ->limit($pages->limit)
            ->all();

从上面的代码中,如果我将对象与findBySql()一起使用,那么它会给我正确的行数,但是行数与$ pages-> totalCount值不匹配。 totalCount给出的数字与实际结果行数不同。

如果使用带有find()的注释对象,那么它为$ pages-> totalCount和$ data_rows提供相同的行号。

我需要在此更新以确保findBySql()按预期工作?

我必须使用findBySql(),因为我的SQL有点复杂,包含多个连接操作。

提前谢谢..

3 个答案:

答案 0 :(得分:2)

尝试像这样获取totatCount

 $find_query = "SELECT * FROM business WHERE status='Enabled' ";

 $query = Business::findBySql($find_query);

//$query = Business::find()->where(['status' => 'Enabled']);

$countQuery = count($query->all());

$pages = new Pagination(['totalCount' => $countQuery, 'defaultPageSize' => 10]);

$data_rows = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();

答案 1 :(得分:1)

来自the forum

  

请注意,由于已经指定了SQL语句,因此在创建的yii \ db \ ActiveQuery实例上调用其他查询修改方法(例如where(),order())将无效。

尝试使用Yii::$app->db->createCommand()

答案 2 :(得分:0)

由于您已指定SQL语句,因此调用offsetlimit将无效。因此,使用查询构建器构建查询。以下应该工作

$query = Business::find()->where(['status' => 'Enabled']);

$pages = new Pagination(['totalCount' => $query->count(), 'defaultPageSize' => 10]);

$data_rows = $query->offset($pages->offset)
        ->limit($pages->limit)
        ->all();