summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/orm/src/UnionQuery.php
blob: 1229ff2bd71cde618d98255b5e789e9ea7d899f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

namespace ipl\Orm;

use ipl\Sql\Select;

class UnionQuery extends Query
{
    /** @var Query[] Underlying queries */
    private $unions;

    /**
     * Get the underlying queries
     *
     * @return Query[]
     */
    public function getUnions()
    {
        if ($this->unions === null) {
            $this->unions = [];

            foreach ($this->getModel()->getUnions() as list($target, $relations, $columns)) {
                $query = (new Query())
                    ->setDb($this->getDb())
                    ->setModel(new $target())
                    ->columns($columns)
                    ->disableDefaultSort()
                    ->with($relations);

                $this->unions[] = $query;
            }
        }

        return $this->unions;
    }

    public function getSelectBase()
    {
        if ($this->selectBase === null) {
            $this->selectBase = new Select();
        }

        $union = new Select();

        foreach ($this->getUnions() as $query) {
            $select = $query->assembleSelect();
            $columns = $select->getColumns();
            $select->resetColumns();
            ksort($columns);
            $select->columns($columns);

            $union->unionAll($select);
        }

        $this->selectBase->from([$this->getModel()->getTableName() => $union]);

        return $this->selectBase;
    }
}