簡體   English   中英

Yii 2分頁無法正常工作

[英]Yii 2 pagination is not working properly

我正在嘗試使分頁在我的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有點復雜,其中包含多個聯接操作。

提前謝謝..

嘗試像這樣獲取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();

論壇

請注意,由於已經指定了SQL語句,因此在創建的yii \\ db \\ ActiveQuery實例上調用其他查詢修改方法(例如where(),order())將無效。

嘗試使用Yii::$app->db->createCommand()

由於您已指定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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM