ActiveQuery.php 6.78 KB
Newer Older
1 2 3 4 5 6 7 8
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\elasticsearch;
Carsten Brandt committed
9

10 11
use yii\db\ActiveQueryInterface;
use yii\db\ActiveQueryTrait;
12 13

/**
14
 * ActiveQuery represents a [[Query]] associated with an [[ActiveRecord]] class.
15
 *
16
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]].
17 18 19 20 21 22 23
 *
 * ActiveQuery mainly provides the following methods to retrieve the query results:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
 * - [[count()]]: returns the number of records.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
24
 * - [[column()]]: returns the value of the first column in the query result.
25 26
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
 *
27 28
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
 * [[orderBy()]] to customize the query options.
29 30 31 32 33 34 35 36 37 38 39 40 41
 *
 * ActiveQuery also provides the following additional query options:
 *
 * - [[with()]]: list of relations that this query should be performed with.
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
 * - [[asArray()]]: whether to return each record as an array.
 *
 * These options can be configured using methods of the same name. For example:
 *
 * ~~~
 * $customers = Customer::find()->with('orders')->asArray()->all();
 * ~~~
 *
42 43 44
 * NOTE: elasticsearch limits the number of records returned to 10 records by default.
 * If you expect to get more records you should specify limit explicitly.
 *
45 46 47
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
48
class ActiveQuery extends Query implements ActiveQueryInterface
49
{
50
	use ActiveQueryTrait;
51 52

	/**
53 54 55 56
	 * Creates a DB command that can be used to execute this query.
	 * @param Connection $db the DB connection used to create the DB command.
	 * If null, the DB connection returned by [[modelClass]] will be used.
	 * @return Command the created DB command instance.
57
	 */
58
	public function createCommand($db = null)
59
	{
60
		/** @var ActiveRecord $modelClass */
61 62 63
		$modelClass = $this->modelClass;
		if ($db === null) {
			$db = $modelClass::getDb();
64 65
		}

66 67 68 69 70 71
		if ($this->type === null) {
			$this->type = $modelClass::type();
		}
		if ($this->index === null) {
			$this->index = $modelClass::index();
			$this->type = $modelClass::type();
72
		}
73 74
		$commandConfig = $db->getQueryBuilder()->build($this);
		return $db->createCommand($commandConfig);
75 76 77
	}

	/**
78 79 80 81
	 * Executes query and returns all results as an array.
	 * @param Connection $db the DB connection used to create the DB command.
	 * If null, the DB connection returned by [[modelClass]] will be used.
	 * @return array the query results. If the query results in nothing, an empty array will be returned.
82
	 */
83
	public function all($db = null)
84
	{
85 86
		$result = $this->createCommand($db)->search();
		if (empty($result['hits']['hits'])) {
87 88
			return [];
		}
89 90 91 92 93 94 95
		if ($this->fields !== null) {
			foreach ($result['hits']['hits'] as &$row) {
				$row['_source'] = isset($row['fields']) ? $row['fields'] : [];
				unset($row['fields']);
			}
			unset($row);
		}
96 97
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;
98
		$pk = $modelClass::primaryKey()[0];
99 100
		if ($this->asArray && $this->indexBy) {
			foreach ($result['hits']['hits'] as &$row) {
101 102 103 104
				if ($pk === '_id') {
					$row['_source']['_id'] = $row['_id'];
				}
				$row['_source']['_score'] = $row['_score'];
105 106
				$row = $row['_source'];
			}
107
			unset($row);
108
		}
Carsten Brandt committed
109
		$models = $this->createModels($result['hits']['hits']);
110
		if ($this->asArray && !$this->indexBy) {
111
			foreach($models as $key => $model) {
112 113 114 115
				if ($pk === '_id') {
					$model['_source']['_id'] = $model['_id'];
				}
				$model['_source']['_score'] = $model['_score'];
116 117 118
				$models[$key] = $model['_source'];
			}
		}
119 120
		if (!empty($this->with)) {
			$this->findWith($this->with, $models);
121
		}
122 123 124 125 126
		if (!$this->asArray) {
			foreach($models as $model) {
				$model->afterFind();
			}
		}
127
		return $models;
128 129 130
	}

	/**
131 132 133 134 135 136
	 * Executes query and returns a single row of result.
	 * @param Connection $db the DB connection used to create the DB command.
	 * If null, the DB connection returned by [[modelClass]] will be used.
	 * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
	 * the query result may be either an array or an ActiveRecord object. Null will be returned
	 * if the query results in nothing.
137
	 */
138
	public function one($db = null)
139
	{
Carsten Brandt committed
140
		if (($result = parent::one($db)) === false) {
141 142
			return null;
		}
143
		if ($this->asArray) {
144 145
			/** @var ActiveRecord $modelClass */
			$modelClass = $this->modelClass;
Carsten Brandt committed
146
			$model = $result['_source'];
147
			$pk = $modelClass::primaryKey()[0];
148 149 150 151
			if ($pk === '_id') {
				$model['_id'] = $result['_id'];
			}
			$model['_score'] = $result['_score'];
152 153 154
		} else {
			/** @var ActiveRecord $class */
			$class = $this->modelClass;
155 156
			$model = $class::instantiate($result);
			$class::populateRecord($model, $result);
157 158 159 160 161 162
		}
		if (!empty($this->with)) {
			$models = [$model];
			$this->findWith($this->with, $models);
			$model = $models[0];
		}
163 164 165
		if (!$this->asArray) {
			$model->afterFind();
		}
166
		return $model;
167
	}
168

169
	/**
Qiang Xue committed
170
	 * @inheritdoc
171 172 173 174 175
	 */
	public function search($db = null, $options = [])
	{
		$result = $this->createCommand($db)->search($options);
		if (!empty($result['hits']['hits'])) {
Carsten Brandt committed
176
			$models = $this->createModels($result['hits']['hits']);
177
			if ($this->asArray) {
178 179
				/** @var ActiveRecord $modelClass */
				$modelClass = $this->modelClass;
180
				$pk = $modelClass::primaryKey()[0];
181
				foreach($models as $key => $model) {
182 183 184 185
					if ($pk === '_id') {
						$model['_source']['_id'] = $model['_id'];
					}
					$model['_source']['_score'] = $model['_score'];
186 187 188 189 190 191
					$models[$key] = $model['_source'];
				}
			}
			if (!empty($this->with)) {
				$this->findWith($this->with, $models);
			}
192 193 194 195 196
			if (!$this->asArray) {
				foreach($models as $model) {
					$model->afterFind();
				}
			}
197 198 199 200 201
			$result['hits']['hits'] = $models;
		}
		return $result;
	}

202
	/**
Qiang Xue committed
203
	 * @inheritdoc
204 205 206 207 208
	 */
	public function scalar($field, $db = null)
	{
		$record = parent::one($db);
		if ($record !== false) {
209
			if ($field == '_id') {
210 211 212 213 214 215 216 217 218
				return $record['_id'];
			} elseif (isset($record['_source'][$field])) {
				return $record['_source'][$field];
			}
		}
		return null;
	}

	/**
Qiang Xue committed
219
	 * @inheritdoc
220 221 222
	 */
	public function column($field, $db = null)
	{
223
		if ($field == '_id') {
224 225
			$command = $this->createCommand($db);
			$command->queryParts['fields'] = [];
226 227 228 229 230 231 232
			$result = $command->search();
			if (empty($result['hits']['hits'])) {
				return [];
			}
			$column = [];
			foreach ($result['hits']['hits'] as $row) {
				$column[] = $row['_id'];
233
			}
234
			return $column;
235 236 237
		}
		return parent::column($field, $db);
	}
238
}