嗨,大家好,我使用下面的代码和limit
不工作,但如果我看到命令比它显示limit
在,但是当我通过查询来ActiveDataProvider
它获取的所有记录
$data= User::find()->where(['category_id'=> 5])->orderBy(['rand()' => SORT_DESC])->limit(4);
$command = $data->createCommand();
$data2 = $command->queryAll();// This works fine and fetch only 4 data
$dataProvider = new ActiveDataProvider([
'query' => $data,
]); // But this displays all data without limit
什么是错的我在做什么这里???
这里是准备在模型时,会发生什么yii\data\ActiveDataProvider
:
/**
* @inheritdoc
*/
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->totalCount = $this->getTotalCount();
$query->limit($pagination->getLimit())->offset($pagination->getOffset());
}
if (($sort = $this->getSort()) !== false) {
$query->addOrderBy($sort->getOrders());
}
return $query->all($this->db);
}
我们感兴趣的是这一部分:
if (($pagination = $this->getPagination()) !== false) {
$pagination->totalCount = $this->getTotalCount();
$query->limit($pagination->getLimit())->offset($pagination->getOffset());
}
所以你可以看到,如果分页是不是false
,限制自动管理。
你可以只设置分页到false
限制将工作的,然后手动设置:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => false,
]);
您可以在ActiveDataProvider使用极限和保持分页 ,像这样: -
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 50,
],
]);
$dataProvider->setTotalCount(1000);
这将使$this->getTotalCount() = 1000
和保持分页。 走在这里和这里更多的参考。