简体   繁体   English

Yii 2分页无法正常工作

[英]Yii 2 pagination is not working properly

I am trying to make pagination workable in my web application. 我正在尝试使分页在我的Web应用程序中可行。 But it seems not not giving me correct number for totalCount properties. 但是,似乎没有为totalCount属性提供正确的数字。 My code is- 我的代码是-

    $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();

From above code, if I use object with findBySql() then it's giving me right number of rows but then the number of rows is not matching with $pages->totalCount value. 从上面的代码中,如果我将对象与findBySql()一起使用,则它为我提供了正确的行数,但是行数与$ pages-> totalCount值不匹配。 totalCount giving me different number than actual result rows number. totalCount给了我与实际结果行号不同的数字。

If use commented object with find() then its giving me same row number for $pages->totalCount and $data_rows. 如果将注释对象与find()一起使用,则它为$ pages-> totalCount和$ data_rows提供相同的行号。

What I need to update here to make sure findBySql() is working as expected? 我需要在此处进行更新以确保findBySql()能够按预期工作吗?

I have to use findBySql() because my SQL is little bit complex which contains multiple join operation. 我必须使用findBySql(),因为我的SQL有点复杂,其中包含多个联接操作。

Advance thanks.. 提前谢谢..

Try to get the totatCount like this 尝试像这样获取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();

From the forum : 论坛

Note that because the SQL statement is already specified, calling additional query modification methods (such as where(), order()) on the created yii\\db\\ActiveQuery instance will have no effect. 请注意,由于已经指定了SQL语句,因此在创建的yii \\ db \\ ActiveQuery实例上调用其他查询修改方法(例如where(),order())将无效。

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

Since you have specified the SQL Statement, calling offset , limit will not work. 由于您已指定SQL语句,因此调用offsetlimit将不起作用。 So build query using query builders. 因此,使用查询构建器构建查询。 Following should work 以下应该工作

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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