LIMIT 在 ActiveDataProvider 中不起作用

LIMIT is not working in ActiveDataProvider

我正在使用以下代码,但 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,
]); 

您可以在 ActiveDataProvider 中使用 Limit 并像这样保持 Pagination:-

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

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