ActiveQuery.php 6.34 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 42 43 44
 *
 * 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();
 * ~~~
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
45
class ActiveQuery extends Query implements ActiveQueryInterface
46
{
47
	use ActiveQueryTrait;
48 49

	/**
50 51 52 53
	 * 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.
54
	 */
55
	public function createCommand($db = null)
56
	{
57
		/** @var ActiveRecord $modelClass */
58 59 60
		$modelClass = $this->modelClass;
		if ($db === null) {
			$db = $modelClass::getDb();
61 62
		}

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

	/**
75 76 77 78
	 * 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.
79
	 */
80
	public function all($db = null)
81
	{
82 83
		$result = $this->createCommand($db)->search();
		if (empty($result['hits']['hits'])) {
84 85
			return [];
		}
86 87 88 89 90 91 92
		if ($this->fields !== null) {
			foreach ($result['hits']['hits'] as &$row) {
				$row['_source'] = isset($row['fields']) ? $row['fields'] : [];
				unset($row['fields']);
			}
			unset($row);
		}
93 94
		/** @var ActiveRecord $modelClass */
		$modelClass = $this->modelClass;
95
		$pk = $modelClass::primaryKey()[0];
96 97
		if ($this->asArray && $this->indexBy) {
			foreach ($result['hits']['hits'] as &$row) {
98 99 100 101
				if ($pk === '_id') {
					$row['_source']['_id'] = $row['_id'];
				}
				$row['_source']['_score'] = $row['_score'];
102 103
				$row = $row['_source'];
			}
104
			unset($row);
105 106 107
		}
		$models = $this->createModels($result['hits']['hits']);
		if ($this->asArray && !$this->indexBy) {
108
			foreach($models as $key => $model) {
109 110 111 112
				if ($pk === '_id') {
					$model['_source']['_id'] = $model['_id'];
				}
				$model['_source']['_score'] = $model['_score'];
113 114 115
				$models[$key] = $model['_source'];
			}
		}
116 117
		if (!empty($this->with)) {
			$this->findWith($this->with, $models);
118
		}
119
		return $models;
120 121 122
	}

	/**
123 124 125 126 127 128
	 * 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.
129
	 */
130
	public function one($db = null)
131
	{
Carsten Brandt committed
132
		if (($result = parent::one($db)) === false) {
133 134
			return null;
		}
135
		if ($this->asArray) {
136 137
			/** @var ActiveRecord $modelClass */
			$modelClass = $this->modelClass;
Carsten Brandt committed
138
			$model = $result['_source'];
139
			$pk = $modelClass::primaryKey()[0];
140 141 142 143
			if ($pk === '_id') {
				$model['_id'] = $result['_id'];
			}
			$model['_score'] = $result['_score'];
144 145 146
		} else {
			/** @var ActiveRecord $class */
			$class = $this->modelClass;
Carsten Brandt committed
147
			$model = $class::create($result);
148 149 150 151 152 153 154
		}
		if (!empty($this->with)) {
			$models = [$model];
			$this->findWith($this->with, $models);
			$model = $models[0];
		}
		return $model;
155
	}
156

157
	/**
Qiang Xue committed
158
	 * @inheritdoc
159 160 161 162 163 164 165
	 */
	public function search($db = null, $options = [])
	{
		$result = $this->createCommand($db)->search($options);
		if (!empty($result['hits']['hits'])) {
			$models = $this->createModels($result['hits']['hits']);
			if ($this->asArray) {
166 167
				/** @var ActiveRecord $modelClass */
				$modelClass = $this->modelClass;
168
				$pk = $modelClass::primaryKey()[0];
169
				foreach($models as $key => $model) {
170 171 172 173
					if ($pk === '_id') {
						$model['_source']['_id'] = $model['_id'];
					}
					$model['_source']['_score'] = $model['_score'];
174 175 176 177 178 179 180 181 182 183 184
					$models[$key] = $model['_source'];
				}
			}
			if (!empty($this->with)) {
				$this->findWith($this->with, $models);
			}
			$result['hits']['hits'] = $models;
		}
		return $result;
	}

185
	/**
Qiang Xue committed
186
	 * @inheritdoc
187 188 189 190 191
	 */
	public function scalar($field, $db = null)
	{
		$record = parent::one($db);
		if ($record !== false) {
192
			if ($field == '_id') {
193 194 195 196 197 198 199 200 201
				return $record['_id'];
			} elseif (isset($record['_source'][$field])) {
				return $record['_source'][$field];
			}
		}
		return null;
	}

	/**
Qiang Xue committed
202
	 * @inheritdoc
203 204 205
	 */
	public function column($field, $db = null)
	{
206
		if ($field == '_id') {
207 208
			$command = $this->createCommand($db);
			$command->queryParts['fields'] = [];
209 210 211 212 213 214 215
			$result = $command->search();
			if (empty($result['hits']['hits'])) {
				return [];
			}
			$column = [];
			foreach ($result['hits']['hits'] as $row) {
				$column[] = $row['_id'];
216
			}
217
			return $column;
218 219 220
		}
		return parent::column($field, $db);
	}
221
}