active-record icon indicating copy to clipboard operation
active-record copied to clipboard

Add method getFinalQuery() to ActiveDataProvider

Open vitalyspirin opened this issue 7 years ago • 2 comments
trafficstars

Currently ActiveDataProvider takes several arguments: query, sort, pagination and then inside function prepareModels() it builds final query and executes it: https://github.com/yiisoft/yii2/blob/master/framework/data/ActiveDataProvider.php#L99

After that I want to get that final query. If building final query (adding things for pagination and sorting) could be moved to another (public) function then it would easier to use it.

Right now the workaround could be to extend ActiveDataProvider and overload prepareModels(). Quite a cumbersome solution for something that could be solved with simple refactoring.

Additional info

Q A
Yii version 2.0.14-dev
PHP version 7.1.12
Operating system Debian 7.3.0-1

vitalyspirin avatar Feb 23 '18 23:02 vitalyspirin

Do you mean to split (protected) prepareModels into 2 methods: the first to prepare the query and the last to prepare the models.

Such as:

public function prepareQuery()
{
    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();
        if ($pagination->totalCount === 0) {
            return [];
        }
        $query->limit($pagination->getLimit())->offset($pagination->getOffset());
    }
    if (($sort = $this->getSort()) !== false) {
        $query->addOrderBy($sort->getOrders());
    }
    return $query;
}
protected function prepareModels()
{
    $query = $this->prepareQuery();
    return $query->all($this->db);
}

To obtain the query : $dataProvider->prepareQuery();

fcaldarelli avatar Mar 09 '18 00:03 fcaldarelli

See https://github.com/yiisoft/yii2/pull/17073

samdark avatar Sep 17 '19 22:09 samdark