lithium\data\source\database\adapter\PostgreSql::_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.

Parameters

  • object $query

    The query object.

Returns

array

The exported query returned by reference.

Source

	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', [
					'limit' => null, 'order' => null,
					'fields' => implode(', ', $fields)
				] + $data);
				$command = rtrim($command, ';');

				$command = $this->renderCommand('read', [
					'source' => "( $command ) AS _TEMP_",
					'fields' => '_ID_',
					'order' => "ORDER BY " . implode(', ', $orders),
					'limit' => $data['limit'],
				]);
			} else {
				$command = $this->renderCommand('read', [
					'fields' => "DISTINCT({$pk}) AS _ID_"
				] + $data);
			}

			$result = $this->_execute($command);
			$ids = [];

			foreach ($result as $row) {
				$ids[] = $row[0];
			}
			if (!$ids) {
				$data = null;
				break;
			}

			$conditions = [];
			$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(
				[$pk => $ids] + $conditions, $query
			);

			$data['limit'] = '';
			break;
		}
		return $data;
	}