|
11 | 11 | use yii\base\Model; |
12 | 12 | use yii\db\ActiveQueryInterface; |
13 | 13 | use yii\db\Connection; |
| 14 | +use yii\db\Query; |
14 | 15 | use yii\db\QueryInterface; |
15 | 16 | use yii\di\Instance; |
16 | 17 |
|
@@ -93,14 +94,40 @@ public function init() |
93 | 94 | } |
94 | 95 |
|
95 | 96 | /** |
96 | | - * {@inheritdoc} |
| 97 | + * Creates a wrapper of [[query]] that allows adding limit and order. |
| 98 | + * @return QueryInterface |
| 99 | + * @throws InvalidConfigException |
97 | 100 | */ |
98 | | - protected function prepareModels() |
| 101 | + protected function createQueryWrapper(): QueryInterface |
99 | 102 | { |
100 | 103 | if (!$this->query instanceof QueryInterface) { |
101 | 104 | 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.'); |
102 | 105 | } |
103 | | - $query = clone $this->query; |
| 106 | + $wrapper = clone $this->query; |
| 107 | + if ($wrapper instanceof Query && !empty($wrapper->union)) { |
| 108 | + $wrapper->where = []; |
| 109 | + $wrapper->limit = null; |
| 110 | + $wrapper->offset = null; |
| 111 | + $wrapper->orderBy = []; |
| 112 | + $wrapper->selectOption = null; |
| 113 | + $wrapper->distinct = false; |
| 114 | + $wrapper->groupBy = []; |
| 115 | + $wrapper->join = []; |
| 116 | + $wrapper->having = []; |
| 117 | + $wrapper->union = []; |
| 118 | + $wrapper->params = []; |
| 119 | + $wrapper->withQueries = []; |
| 120 | + $wrapper->select('*')->from(['q' => $this->query]); |
| 121 | + } |
| 122 | + return $wrapper; |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * {@inheritdoc} |
| 127 | + */ |
| 128 | + protected function prepareModels() |
| 129 | + { |
| 130 | + $query = $this->createQueryWrapper(); |
104 | 131 | if (($pagination = $this->getPagination()) !== false) { |
105 | 132 | $pagination->totalCount = $this->getTotalCount(); |
106 | 133 | if ($pagination->totalCount === 0) { |
@@ -161,11 +188,7 @@ protected function prepareKeys($models) |
161 | 188 | */ |
162 | 189 | protected function prepareTotalCount() |
163 | 190 | { |
164 | | - if (!$this->query instanceof QueryInterface) { |
165 | | - 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.'); |
166 | | - } |
167 | | - $query = clone $this->query; |
168 | | - return (int) $query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db); |
| 191 | + return (int) $this->createQueryWrapper()->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db); |
169 | 192 | } |
170 | 193 |
|
171 | 194 | /** |
|
0 commit comments