嗨,大家好,我正在使用以下代码,而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,
]);
关于yii2 - LIMIT在ActiveDataProvider中不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33748211/