大家好我正在使用以下代码且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
我在这里做错了什么???
答案 0 :(得分:24)
以下是在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,
]);
答案 1 :(得分:3)