lithium\data\source\database\adapter\PostgreSql::_queryExport PHP Method

_queryExport() protected method

Helper method for Database::read() to export query while handling additional joins when using relationships and limited result sets. Filters conditions on subsequent queries to just the ones applying to the relation.
See also: lithium\data\source\Database::read()
protected _queryExport ( object $query ) : array
$query object The query object.
return array The exported query returned by reference.
    protected function &_queryExport($query)
    {
        $data = $query->export($this);
        if (!$query->limit() || !($model = $query->model())) {
            return $data;
        }
        foreach ($query->relationships() as $relation) {
            if ($relation['type'] !== 'hasMany') {
                continue;
            }
            $pk = $this->name($model::meta('name') . '.' . $model::key());
            if ($query->order()) {
                list($fields, $orders) = $this->_distinctExport($query);
                array_unshift($fields, "DISTINCT ON({$pk}) {$pk} AS _ID_");
                $command = $this->renderCommand('read', array('limit' => null, 'order' => null, 'fields' => implode(', ', $fields)) + $data);
                $command = rtrim($command, ';');
                $command = $this->renderCommand('read', array('source' => "( {$command} ) AS _TEMP_", 'fields' => '_ID_', 'order' => "ORDER BY " . implode(', ', $orders), 'limit' => $data['limit']));
            } else {
                $command = $this->renderCommand('read', array('fields' => "DISTINCT({$pk}) AS _ID_") + $data);
            }
            $result = $this->_execute($command);
            $ids = array();
            foreach ($result as $row) {
                $ids[] = $row[0];
            }
            if (!$ids) {
                $data = null;
                break;
            }
            $conditions = array();
            $relations = array_keys($query->relationships());
            $pattern = '/^(' . implode('|', $relations) . ')\\./';
            foreach ($query->conditions() as $key => $value) {
                if (preg_match($pattern, $key)) {
                    $conditions[$key] = $value;
                }
            }
            $data['conditions'] = $this->conditions(array($pk => $ids) + $conditions, $query);
            $data['limit'] = '';
            break;
        }
        return $data;
    }