LIMIT不ActiveDataProvider工作LIMIT不ActiveDataProvider

2019-05-12 04:57发布

嗨,大家好,我使用下面的代码和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

什么是错的我在做什么这里???

Answer 1:

这里是准备在模型时,会发生什么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,
]); 


Answer 2:

您可以在ActiveDataProvider使用极限和保持分页 ,像这样: -

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

这将使$this->getTotalCount() = 1000和保持分页。 走在这里和这里更多的参考。



文章来源: LIMIT is not working in ActiveDataProvider