Skip to content

Commit

Permalink
Update ActiveDataProvider::prepareModels() to avoid SQL error with UN…
Browse files Browse the repository at this point in the history
…ION queries

As for issue yiisoft#20239, move order by and limit clauses to the last UNION query to avoid SQL errors on UNION queries
  • Loading branch information
cepaim authored Aug 16, 2024
1 parent 34d2396 commit 6356e60
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions framework/data/ActiveDataProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,29 @@ protected function prepareModels()
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;

$has_union = $query->union && count($query->union);
if (($pagination = $this->getPagination()) !== false) {
$pagination->totalCount = $this->getTotalCount();
if ($pagination->totalCount === 0) {
return [];
}
$query->limit($pagination->getLimit())->offset($pagination->getOffset());
if ($has_union) {
$query->union[count($query->union)-1]['query']->limit($pagination->getLimit())->offset($pagination->getOffset());
} else {
$query->limit($pagination->getLimit())->offset($pagination->getOffset());
}
}
if (($sort = $this->getSort()) !== false) {
$query->addOrderBy($sort->getOrders());
}
if ($has_union) {
if ($query->orderBy) {
$query->union[count($query->union)-1]['query']->addOrderBy($query->orderBy);
$query->orderBy = null;
}
}

return $query->all($this->db);
}

Expand Down

0 comments on commit 6356e60

Please sign in to comment.