有一个巨大的数据库表,有数百万行,它需要在GridView中输出,在分页器中只有前一个和下一个链接。
我不想在这样的表上使用'select count(*)',所以没有TotalCount。我还想防止用户设置巨大的偏移量,降低MySQL的性能。
有人能帮我吗?
创建数据提供程序时,请确保将totalCount指定为一个数字,例如0,这将防止Yii运行count(*)查询。
你应该为yii'widgets'Linkpager创建一个替换类,它只生成你想要显示的链接。
最后,将您的寻呼机附加到GridView。
<?php GridView::widget([
'dataProvider'=>$dataProvider,
'pager' => [
'class' => 'path'to'my'custom'Pager''
]
'columns' =>
....
]; ?>
我已经等了好几天,以确保我没有错过一些明显的解决方案,但现在需要我自己硬编码它。我发现最快的方法是扩展DataProvider并重写方法:prepareTotalCount()
, prepareModels()
:
namespace common;
use yii'data'ActiveDataProvider;
use yii'base'InvalidConfigException;
use yii'db'QueryInterface;
class BigActiveDataProvider extends ActiveDataProvider
{
protected function prepareTotalCount() {
return 0;
}
protected function prepareModels()
{
if (!$this->query instanceof QueryInterface) {
throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii'db'Query or its subclasses.');
}
$query = clone $this->query;
if (($pagination = $this->getPagination()) !== false) {
$pagination->validatePage = false;
$page = $pagination->getPage(true) + 1;
$offset = $page*$pagination->getPageSize();
$query->limit($pagination->getLimit() + 1)->offset($offset);
}
if (($sort = $this->getSort()) !== false) {
$query->addOrderBy($sort->getOrders());
}
$res = $query->all($this->db);
if (($pagination = $this->getPagination()) !== false) {
$pagination->totalCount = ($page)*$pagination->getPageSize();
if (count($res) > $pagination->getPageSize()) {
unset($res[count($res)-1]);
$pagination->totalCount++;
}
}
return $res;
}
}
我不认为这是最好的解决方案,但它按计划工作,它不限制ActiveDataProvider
的能力。它只确保count(*)查询不会被执行,并且不需要设置totalCount
。