LIMIT is not working in ActiveDataProvider

妖精的绣舞 提交于 2019-11-26 14:35:39

问题


Hi guys i am using following code and the limit doesnt work, but if i see the command than it shows limit in that but when i pass the query to ActiveDataProvider it fetch all the records

$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

What is wrong i am doing here???


回答1:


Here is what happens when preparing models in 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);
}

We're interested in this part:

if (($pagination = $this->getPagination()) !== false) {
    $pagination->totalCount = $this->getTotalCount();
    $query->limit($pagination->getLimit())->offset($pagination->getOffset());
}

So as you can see if pagination is not false, limit is managed automatically.

You can just set pagination to false and then manual setting of limit will work:

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => false,
]); 



回答2:


You can use Limit in the ActiveDataProvider and keep Pagination like so:-

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

This will make $this->getTotalCount() = 1000 and Keep the pagination. Go here and here for more reference.



来源:https://stackoverflow.com/questions/33748211/limit-is-not-working-in-activedataprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!