LIMIT在ActiveDataProvider中不起作用

时间:2015-11-17 02:38:22

标签: yii2 yii2-advanced-app yii2-basic-app

大家好我正在使用以下代码且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

我在这里做错了什么???

2 个答案:

答案 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)

您可以在 ActiveDataProvider 中使用Limit,并保持分页,如下所示:-

$dataProvider = new ActiveDataProvider([
        'query' => $query,
         'pagination' => [
             'pageSize' => 50, 
         ],
    ]);
$dataProvider->setTotalCount(1000);

这将使$this->getTotalCount() = 1000并保持分页。 转到herehere以获取更多参考。