| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Orm; |
| 4 |
|
| 5 |
use ipl\Sql\Select; |
| 6 |
|
| 7 |
class UnionQuery extends Query |
| 8 |
{ |
| 9 |
/** @var ?Query[] Underlying queries */ |
| 10 |
private ?array $unions = null; |
| 11 |
|
| 12 |
/** |
| 13 |
* Get the underlying queries |
| 14 |
* |
| 15 |
* @return Query[] |
| 16 |
*/ |
| 17 |
public function getUnions(): array |
| 18 |
{ |
| 19 |
if ($this->unions === null) { |
| 20 |
$this->unions = []; |
| 21 |
|
| 22 |
/** @var UnionModel $model */ |
| 23 |
$model = $this->getModel(); |
| 24 |
foreach ($model->getUnions() as [$target, $relations, $columns]) { |
| 25 |
/** @var class-string<Model> $target */ |
| 26 |
$query = $target::on($this->getDb()) |
| 27 |
->columns($columns) |
| 28 |
->disableDefaultSort() |
| 29 |
->with($relations); |
| 30 |
|
| 31 |
$this->unions[] = $query; |
| 32 |
} |
| 33 |
} |
| 34 |
|
| 35 |
return $this->unions; |
| 36 |
} |
| 37 |
|
| 38 |
public function getSelectBase(): Select |
| 39 |
{ |
| 40 |
if ($this->selectBase === null) { |
| 41 |
$this->selectBase = new Select(); |
| 42 |
} |
| 43 |
|
| 44 |
$union = new Select(); |
| 45 |
|
| 46 |
foreach ($this->getUnions() as $query) { |
| 47 |
$select = $query->assembleSelect(); |
| 48 |
$columns = $select->getColumns(); |
| 49 |
$select->resetColumns(); |
| 50 |
ksort($columns); |
| 51 |
$select->columns($columns); |
| 52 |
|
| 53 |
$union->unionAll($select); |
| 54 |
} |
| 55 |
|
| 56 |
$this->selectBase->from([$this->getModel()->getTableName() => $union]); |
| 57 |
|
| 58 |
return $this->selectBase; |
| 59 |
} |
| 60 |
} |