LIMIT 在 ActiveDataProvider 中不起作用 [英] LIMIT is not working in ActiveDataProvider

查看:21
本文介绍了LIMIT 在 ActiveDataProvider 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码并且 limit 不起作用.但是,如果我看到命令而不是其中显示的 limit,但是当我将查询传递给 ActiveDataProvider 时,它会获取所有记录:

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

我在这里做错了什么?

推荐答案

这是在 yii\data\ActiveDataProvider 中准备模型时发生的情况:

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);
}

我们对这部分感兴趣:

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

所以你可以看到如果分页不是false,限制是自动管理的.

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

您可以将分页设置为 false,然后手动设置限制即可:

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

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

这篇关于LIMIT 在 ActiveDataProvider 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆