lithium\data\source\Database::read()

public method

Reads records from a database using a lithium\data\model\Query object or raw SQL string.

Parameters

  • string|object $query

    lithium\data\model\Query object or SQL string.

  • array $options

    If $query is a raw string, contains the values that will be escaped and quoted. Other options:

    • 'return' string: switch return between 'array', 'item', or 'resource' string: Defaults to 'item'.

Returns

mixed

Determined by $options['return'].

Filter

This method can be filtered.

Source

	public function read($query, array $options = []) {
		$defaults = [
			'return' => is_string($query) ? 'array' : 'item',
			'schema' => null,
			'quotes' => $this->_quotes
		];
		$options += $defaults;

		$params = compact('query', 'options');

		return Filters::run($this, __FUNCTION__, $params, function($params) {
			$query = $params['query'];
			$args = $params['options'];
			$return = $args['return'];
			unset($args['return']);

			$model = is_object($query) ? $query->model() : null;

			if (is_string($query)) {
				$sql = Text::insert($query, $this->value($args));
			} else {
				if (!$data = $this->_queryExport($query)) {
					return false;
				}
				$sql = $this->renderCommand($data['type'], $data);
			}
			$result = $this->_execute($sql);

			if ($return === 'resource') {
				return $result;
			}
			if ($return === 'item') {
				$collection = $model::create([], compact('query', 'result') + [
					'class' => 'set', 'defaults' => false
				]);
			} else {
				$columns = $args['schema'] ?: $this->schema($query, $result);

				if (!is_array(reset($columns))) {
					$columns = ['' => $columns];
				}

				$i = 0;
				$records = [];

				foreach ($result as $data) {
					$offset = 0;
					$records[$i] = [];

					foreach ($columns as $path => $cols) {
						$len = count($cols);
						$values = array_combine($cols, array_slice($data, $offset, $len));
						($path) ? $records[$i][$path] = $values : $records[$i] += $values;
						$offset += $len;
					}
					$i++;
				}
				$collection = Set::expand($records);
			}
			if (is_object($query) && $query->with()) {
				$model::embed($collection, $query->with(), ['return' => $return]);
			}
			return $collection;
		});
	}