BaseActiveQuery.php 2.15 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
<?php
/**
 * ActiveFinder class file.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
 * @copyright Copyright &copy; 2008-2012 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\db\ar;

use yii\db\dao\BaseQuery;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class BaseActiveQuery extends BaseQuery
{
	/**
	 * @var string the name of the ActiveRecord class.
	 */
	public $modelClass;
	/**
	 * @var array list of relations that this query should be performed with
	 */
	public $with;
	/**
	 * @var string the table alias to be used for query
	 */
	public $tableAlias;
	/**
	 * @var string the name of the column that the result should be indexed by.
	 * This is only useful when the query result is returned as an array.
	 */
Qiang Xue committed
37
	public $index;
Qiang Xue committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	/**
	 * @var boolean whether to return each record as an array. If false (default), an object
	 * of [[modelClass]] will be created to represent each record.
	 */
	public $asArray;
	/**
	 * @var array list of scopes that should be applied to this query
	 */
	public $scopes;

	public function asArray($value = true)
	{
		$this->asArray = $value;
		return $this;
	}

	public function with()
	{
		$this->with = func_get_args();
		if (isset($this->with[0]) && is_array($this->with[0])) {
			// the parameter is given as an array
			$this->with = $this->with[0];
		}
		return $this;
	}

Qiang Xue committed
64
	public function index($column)
Qiang Xue committed
65
	{
Qiang Xue committed
66
		$this->index = $column;
Qiang Xue committed
67 68 69 70 71 72 73 74 75 76 77 78 79 80
		return $this;
	}

	public function tableAlias($value)
	{
		$this->tableAlias = $value;
		return $this;
	}

	public function scopes($names)
	{
		$this->scopes = $names;
		return $this;
	}
Qiang Xue committed
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106

	protected function createModels($rows)
	{
		$models = array();
		if ($this->asArray) {
			if ($this->index === null) {
				return $rows;
			}
			foreach ($rows as $row) {
				$models[$row[$this->index]] = $row;
			}
		} else {
			/** @var $class ActiveRecord */
			$class = $this->modelClass;
			if ($this->index === null) {
				foreach ($rows as $row) {
					$models[] = $class::create($row);
				}
			} else {
				foreach ($rows as $row) {
					$models[$row[$this->index]] = $class::create($row);
				}
			}
		}
		return $models;
	}
Qiang Xue committed
107
}