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

namespace yii\sphinx;

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

14
/**
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 * ActiveQuery represents a Sphinx query associated with an Active Record class.
 *
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]] and [[ActiveRecord::findBySql()]].
 *
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
 * [[orderBy()]] to customize the query options.
 *
 * 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:
 *
 * ~~~
 * $articles = Article::find()->with('source')->asArray()->all();
 * ~~~
 *
 * ActiveQuery allows to build the snippets using sources provided by ActiveRecord.
 * You can use [[snippetByModel()]] method to enable this.
 * For example:
 *
 * ~~~
 * class Article extends ActiveRecord
 * {
 *     public function getSource()
 *     {
 *         return $this->hasOne('db', ArticleDb::className(), ['id' => 'id']);
 *     }
 *
 *     public function getSnippetSource()
 *     {
 *         return $this->source->content;
 *     }
 *
 *     ...
 * }
 *
 * $articles = Article::find()->with('source')->snippetByModel()->all();
 * ~~~
56 57 58 59
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
60
class ActiveQuery extends Query implements ActiveQueryInterface
61
{
62 63
	use ActiveQueryTrait;

64 65 66 67 68 69
	/**
	 * @var string the SQL statement to be executed for retrieving AR records.
	 * This is set by [[ActiveRecord::findBySql()]].
	 */
	public $sql;

70
	/**
71
	 * Sets the [[snippetCallback]] to [[fetchSnippetSourceFromModels()]], which allows to
72 73
	 * fetch the snippet source strings from the Active Record models, using method
	 * [[ActiveRecord::getSnippetSource()]].
74 75 76 77 78 79 80 81 82 83 84 85 86 87
	 * For example:
	 *
	 * ~~~
	 * class Article extends ActiveRecord
	 * {
	 *     public function getSnippetSource()
	 *     {
	 *         return file_get_contents('/path/to/source/files/' . $this->id . '.txt');;
	 *     }
	 * }
	 *
	 * $articles = Article::find()->snippetByModel()->all();
	 * ~~~
	 *
88 89 90 91 92
	 * Warning: this option should NOT be used with [[asArray]] at the same time!
	 * @return static the query object itself
	 */
	public function snippetByModel()
	{
93
		$this->snippetCallback([$this, 'fetchSnippetSourceFromModels']);
94 95 96
		return $this;
	}

97 98 99 100 101 102 103 104 105 106 107
	/**
	 * 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.
	 */
	public function all($db = null)
	{
		$command = $this->createCommand($db);
		$rows = $command->queryAll();
		if (!empty($rows)) {
Carsten Brandt committed
108
			$models = $this->createModels($rows);
109
			if (!empty($this->with)) {
Klimov Paul committed
110
				$this->findWith($this->with, $models);
111
			}
112
			$models = $this->fillUpSnippets($models);
113 114 115 116 117
			if (!$this->asArray) {
				foreach($models as $model) {
					$model->afterFind();
				}
			}
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
			return $models;
		} else {
			return [];
		}
	}

	/**
	 * 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.
	 */
	public function one($db = null)
	{
		$command = $this->createCommand($db);
		$row = $command->queryOne();
		if ($row !== false) {
			if ($this->asArray) {
				$model = $row;
			} else {
				/** @var $class ActiveRecord */
				$class = $this->modelClass;
Carsten Brandt committed
142
				$model = $class::create($row);
143
			}
144
			if (!empty($this->with)) {
145
				$models = [$model];
Klimov Paul committed
146
				$this->findWith($this->with, $models);
147
				$model = $models[0];
148
			}
149
			list ($model) = $this->fillUpSnippets([$model]);
150 151 152
			if (!$this->asArray) {
				$model->afterFind();
			}
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
			return $model;
		} else {
			return null;
		}
	}

	/**
	 * 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.
	 */
	public function createCommand($db = null)
	{
		/** @var $modelClass ActiveRecord */
		$modelClass = $this->modelClass;
169 170
		$this->setConnection($db);
		$db = $this->getConnection();
171 172 173 174 175 176 177 178 179 180 181 182 183 184

		$params = $this->params;
		if ($this->sql === null) {
			if ($this->from === null) {
				$tableName = $modelClass::indexName();
				if ($this->select === null && !empty($this->join)) {
					$this->select = ["$tableName.*"];
				}
				$this->from = [$tableName];
			}
			list ($this->sql, $params) = $db->getQueryBuilder()->build($this);
		}
		return $db->createCommand($this->sql, $params);
	}
185 186

	/**
Qiang Xue committed
187
	 * @inheritdoc
188 189 190 191 192 193 194 195 196 197
	 */
	protected function defaultConnection()
	{
		$modelClass = $this->modelClass;
		return $modelClass::getDb();
	}

	/**
	 * Fetches the source for the snippets using [[ActiveRecord::getSnippetSource()]] method.
	 * @param ActiveRecord[] $models raw query result rows.
198
	 * @throws \yii\base\InvalidCallException if [[asArray]] enabled.
199 200 201 202
	 * @return array snippet source strings
	 */
	protected function fetchSnippetSourceFromModels($models)
	{
203 204 205
		if ($this->asArray) {
			throw new InvalidCallException('"' . __METHOD__ . '" unable to determine snippet source from plain array. Either disable "asArray" option or use regular "snippetCallback"');
		}
206 207 208 209 210 211
		$result = [];
		foreach ($models as $model) {
			$result[] = $model->getSnippetSource();
		}
		return $result;
	}
Qiang Xue committed
212
}