Yii 2分页不正常

I am trying to make pagination workable in my web application. But it seems not not giving me correct number for totalCount properties. 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. totalCount giving me different number than actual result rows number.

If use commented object with find() then its giving me same row number for $pages->totalCount and $data_rows.

What I need to update here to make sure findBySql() is working as expected?

I have to use findBySql() because my SQL is little bit complex which contains multiple join operation.

Advance thanks..

Try to get the totatCount like this

 $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.

Try using Yii::$app->db->createCommand()

Since you have specified the SQL Statement, calling offset, limit will not work. 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();