active-record
active-record copied to clipboard
Add method getFinalQuery() to ActiveDataProvider
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 |
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();
See https://github.com/yiisoft/yii2/pull/17073