Commit cc33a930 by Qiang Xue

Finished AR API.

parent 3ca50f30
Because [[ActiveQuery]] implements a set of query building methods,
additional query conditions can be specified by calling the methods of [[ActiveQuery]].
Below are some examples:
~~~
// find all customers
$customers = Customer::find()->all();
// find all active customers and order them by their age:
$customers = Customer::find()
->where(array('status' => 1))
->orderBy('age')
->all();
// find a single customer whose primary key value is 10
$customer = Customer::find(10);
// the above is equivalent to:
$customer = Customer::find()->where(array('id' => 10))->one();
// find a single customer whose age is 30 and whose status is 1
$customer = Customer::find(array('age' => 30, 'status' => 1));
// the above is equivalent to:
$customer = Customer::find()->where(array('age' => 30, 'status' => 1))->one();
~~~
- `beforeInsert`. Raised before the record is saved.
By setting [[\yii\base\ModelEvent::isValid]] to be false, the normal [[save()]] will be stopped.
- `afterInsert`. Raised after the record is saved.
- `beforeUpdate`. Raised before the record is saved.
By setting [[\yii\base\ModelEvent::isValid]] to be false, the normal [[save()]] will be stopped.
- `afterUpdate`. Raised after the record is saved.
- `beforeDelete`. Raised before the record is deleted.
By setting [[\yii\base\ModelEvent::isValid]] to be false, the normal [[delete()]] process will be stopped.
- `afterDelete`. Raised after the record is deleted.
<?php <?php
/** /**
* ActiveFinder class file. * ActiveQuery class file.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/ * @link http://www.yiiframework.com/
...@@ -13,10 +13,41 @@ namespace yii\db; ...@@ -13,10 +13,41 @@ namespace yii\db;
use yii\db\Connection; use yii\db\Connection;
use yii\db\Command; use yii\db\Command;
use yii\db\QueryBuilder; use yii\db\QueryBuilder;
use yii\base\VectorIterator;
use yii\db\Expression; use yii\db\Expression;
use yii\db\Exception; use yii\db\Exception;
/**
* ActiveQuery represents a DB query associated with an Active Record class.
*
* ActiveQuery instances are usually created by [[ActiveRecord::find()]], [[ActiveRecord::findBySql()]]
* and [[ActiveRecord::count()]].
*
* 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.
* - [[value()]]: returns the value of the first column in the first row of the query result.
* - [[exists()]]: returns a value indicating whether the query result has data or not.
*
* 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.
* - [[scopes]]: list of scopes that should be applied to this query.
*
* These options can be configured using methods of the same name. For example:
*
* ~~~
* $customers = Customer::find()->with('orders')->asArray()->all();
* ~~~
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ActiveQuery extends Query class ActiveQuery extends Query
{ {
/** /**
...@@ -28,7 +59,7 @@ class ActiveQuery extends Query ...@@ -28,7 +59,7 @@ class ActiveQuery extends Query
*/ */
public $with; public $with;
/** /**
* @var string the name of the column by which the query result should be indexed. * @var string the name of the column by which query results should be indexed by.
* This is only used when the query result is returned as an array when calling [[all()]]. * This is only used when the query result is returned as an array when calling [[all()]].
*/ */
public $indexBy; public $indexBy;
...@@ -47,6 +78,14 @@ class ActiveQuery extends Query ...@@ -47,6 +78,14 @@ class ActiveQuery extends Query
*/ */
public $sql; public $sql;
/**
* PHP magic method.
* This method is overridden so that scope methods declared in [[modelClass]]
* can be invoked as methods of ActiveQuery.
* @param string $name
* @param array $params
* @return mixed|ActiveQuery
*/
public function __call($name, $params) public function __call($name, $params)
{ {
if (method_exists($this->modelClass, $name)) { if (method_exists($this->modelClass, $name)) {
...@@ -102,10 +141,10 @@ class ActiveQuery extends Query ...@@ -102,10 +141,10 @@ class ActiveQuery extends Query
} }
/** /**
* Returns a scalar value for this query. * Returns the query result as a scalar value.
* The value returned will be the first column in the first row of the query results. * The value returned will be the first column in the first row of the query results.
* @return string|boolean the value of the first column in the first row of the query result. * @return string|boolean the value of the first column in the first row of the query result.
* False is returned if there is no value. * False is returned if the query result is empty.
*/ */
public function value() public function value()
{ {
...@@ -113,8 +152,8 @@ class ActiveQuery extends Query ...@@ -113,8 +152,8 @@ class ActiveQuery extends Query
} }
/** /**
* Executes query and returns if matching row exists in the table. * Returns a value indicating whether the query result contains any row of data.
* @return bool if row exists in the table. * @return boolean whether the query result contains any row of data.
*/ */
public function exists() public function exists()
{ {
...@@ -141,14 +180,7 @@ class ActiveQuery extends Query ...@@ -141,14 +180,7 @@ class ActiveQuery extends Query
$this->from = array($tableName); $this->from = array($tableName);
} }
if (!empty($this->scopes)) { if (!empty($this->scopes)) {
foreach ($this->scopes as $name => $config) { $this->applyScopes($this->scopes);
if (is_integer($name)) {
$modelClass::$config($this);
} else {
array_unshift($config, $this);
call_user_func_array(array($modelClass, $name), $config);
}
}
} }
/** @var $qb QueryBuilder */ /** @var $qb QueryBuilder */
$qb = $db->getQueryBuilder(); $qb = $db->getQueryBuilder();
...@@ -157,12 +189,39 @@ class ActiveQuery extends Query ...@@ -157,12 +189,39 @@ class ActiveQuery extends Query
return $db->createCommand($this->sql, $this->params); return $db->createCommand($this->sql, $this->params);
} }
/**
* Sets the [[asArray]] property.
* @param boolean $value whether to return the query results in terms of arrays instead of Active Records.
* @return ActiveQuery the query object itself
*/
public function asArray($value = true) public function asArray($value = true)
{ {
$this->asArray = $value; $this->asArray = $value;
return $this; return $this;
} }
/**
* Specifies the relations with which this query should be performed.
*
* The parameters to this method can be either one or multiple strings, or a single array
* of relation names and the optional callbacks to customize the relations.
*
* The followings are some usage examples:
*
* ~~~
* // find customers together with their orders and country
* Customer::find()->with('orders', 'country')->all();
* // find customers together with their country and orders of status 1
* Customer::find()->with(array(
* 'orders' => function($query) {
* $query->andWhere('status = 1');
* },
* 'country',
* ))->all();
* ~~~
*
* @return ActiveQuery the query object itself
*/
public function with() public function with()
{ {
$this->with = func_get_args(); $this->with = func_get_args();
...@@ -173,13 +232,39 @@ class ActiveQuery extends Query ...@@ -173,13 +232,39 @@ class ActiveQuery extends Query
return $this; return $this;
} }
/**
* Sets the [[indexBy]] property.
* @param string $column the name of the column by which the query results should be indexed by.
* @return ActiveQuery the query object itself
*/
public function indexBy($column) public function indexBy($column)
{ {
$this->indexBy = $column; $this->indexBy = $column;
return $this; return $this;
} }
public function scopes($names) /**
* Specifies the scopes to be applied to this query.
*
* The parameters to this method can be either one or multiple strings, or a single array
* of scopes names and their corresponding customization parameters.
*
* The followings are some usage examples:
*
* ~~~
* // find all active customers
* Customer::find()->scopes('active')->all();
* // find active customers whose age is greater than 30
* Customer::find()->scopes(array(
* 'active',
* 'olderThan' => array(30),
* ))->all();
* // alternatively the above statement can be written as:
* Customer::find()->active()->olderThan(30)->all();
* ~~~
* @return ActiveQuery the query object itself
*/
public function scopes()
{ {
$this->scopes = func_get_args(); $this->scopes = func_get_args();
if (isset($this->scopes[0]) && is_array($this->scopes[0])) { if (isset($this->scopes[0]) && is_array($this->scopes[0])) {
...@@ -189,7 +274,7 @@ class ActiveQuery extends Query ...@@ -189,7 +274,7 @@ class ActiveQuery extends Query
return $this; return $this;
} }
protected function createModels($rows) private function createModels($rows)
{ {
$models = array(); $models = array();
if ($this->asArray) { if ($this->asArray) {
...@@ -216,7 +301,7 @@ class ActiveQuery extends Query ...@@ -216,7 +301,7 @@ class ActiveQuery extends Query
return $models; return $models;
} }
protected function populateRelations(&$models, $with) private function populateRelations(&$models, $with)
{ {
$primaryModel = new $this->modelClass; $primaryModel = new $this->modelClass;
$relations = $this->normalizeRelations($primaryModel, $with); $relations = $this->normalizeRelations($primaryModel, $with);
...@@ -233,9 +318,8 @@ class ActiveQuery extends Query ...@@ -233,9 +318,8 @@ class ActiveQuery extends Query
* @param ActiveRecord $model * @param ActiveRecord $model
* @param array $with * @param array $with
* @return ActiveRelation[] * @return ActiveRelation[]
* @throws \yii\db\Exception
*/ */
protected function normalizeRelations($model, $with) private function normalizeRelations($model, $with)
{ {
$relations = array(); $relations = array();
foreach ($with as $name => $callback) { foreach ($with as $name => $callback) {
...@@ -268,4 +352,17 @@ class ActiveQuery extends Query ...@@ -268,4 +352,17 @@ class ActiveQuery extends Query
} }
return $relations; return $relations;
} }
private function applyScopes($scopes)
{
$modelClass = $this->modelClass;
foreach ($scopes as $name => $config) {
if (is_integer($name)) {
$modelClass::$config($this);
} else {
array_unshift($config, $this);
call_user_func_array(array($modelClass, $name), $config);
}
}
}
} }
...@@ -12,12 +12,19 @@ namespace yii\db; ...@@ -12,12 +12,19 @@ namespace yii\db;
use yii\db\Connection; use yii\db\Connection;
use yii\db\Command; use yii\db\Command;
use yii\base\BadParamException;
/** /**
* It is used in three scenarios: * ActiveRelation represents a relation between two Active Record classes.
* - eager loading: User::find()->with('posts')->all(); *
* - lazy loading: $user->posts; * ActiveRelation instances are usually created by calling [[ActiveRecord::hasOne()]] and
* - lazy loading with query options: $user->posts()->where('status=1')->get(); * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
* a getter method which calls one of the above methods and returns the created ActiveRelation object.
*
* A relation is specified by [[link]] which represents the association between columns
* of different tables; and the multiplicity of the relation is indicated by [[multiple]].
*
* If a relation involves a pivot table, it may be specified by [[via()]] or [[viaTable()]] method.
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0 * @since 2.0
...@@ -42,15 +49,17 @@ class ActiveRelation extends ActiveQuery ...@@ -42,15 +49,17 @@ class ActiveRelation extends ActiveQuery
*/ */
public $link; public $link;
/** /**
* @var array|ActiveRelation * @var array|ActiveRelation the query associated with the pivot table. Please call [[via()]]
* or [[viaTable()]] to set this property instead of directly setting it.
*/ */
public $via; public $via;
/** /**
* @param string $relationName * Specifies the relation associated with the pivot table.
* @param callback $callback * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
* @return ActiveRelation * @param callback $callback a PHP callback for customizing the relation associated with the pivot table.
* @throws Exception * Its signature should be `function($query)`, where `$query` is the query to be customized.
* @return ActiveRelation the relation object itself.
*/ */
public function via($relationName, $callback = null) public function via($relationName, $callback = null)
{ {
...@@ -63,9 +72,13 @@ class ActiveRelation extends ActiveQuery ...@@ -63,9 +72,13 @@ class ActiveRelation extends ActiveQuery
} }
/** /**
* @param string $tableName * Specifies the pivot table.
* @param array $link * @param string $tableName the name of the pivot table.
* @param callback $callback * @param array $link the link between the pivot table and the table associated with [[primaryModel]].
* The keys of the array represent the columns in the pivot table, and the values represent the columns
* in the [[primaryModel]] table.
* @param callback $callback a PHP callback for customizing the relation associated with the pivot table.
* Its signature should be `function($query)`, where `$query` is the query to be customized.
* @return ActiveRelation * @return ActiveRelation
*/ */
public function viaTable($tableName, $link, $callback = null) public function viaTable($tableName, $link, $callback = null)
...@@ -118,10 +131,18 @@ class ActiveRelation extends ActiveQuery ...@@ -118,10 +131,18 @@ class ActiveRelation extends ActiveQuery
return parent::createCommand($db); return parent::createCommand($db);
} }
/**
* Finds the related records and populates them into the primary models.
* This method is internally by [[ActiveQuery]]. Do not call it directly.
* @param string $name the relation name
* @param array $primaryModels primary models
* @return array the related models
* @throws BadParamException
*/
public function findWith($name, &$primaryModels) public function findWith($name, &$primaryModels)
{ {
if (!is_array($this->link)) { if (!is_array($this->link)) {
throw new \yii\base\Exception('invalid link'); throw new BadParamException('Invalid link: it must be an array of key-value pairs.');
} }
if ($this->via instanceof self) { if ($this->via instanceof self) {
...@@ -173,7 +194,14 @@ class ActiveRelation extends ActiveQuery ...@@ -173,7 +194,14 @@ class ActiveRelation extends ActiveQuery
} }
} }
protected function buildBuckets($models, $link, $viaModels = null, $viaLink = null) /**
* @param array $models
* @param array $link
* @param array $viaModels
* @param array $viaLink
* @return array
*/
private function buildBuckets($models, $link, $viaModels = null, $viaLink = null)
{ {
$buckets = array(); $buckets = array();
$linkKeys = array_keys($link); $linkKeys = array_keys($link);
...@@ -214,7 +242,12 @@ class ActiveRelation extends ActiveQuery ...@@ -214,7 +242,12 @@ class ActiveRelation extends ActiveQuery
return $buckets; return $buckets;
} }
protected function getModelKey($model, $attributes) /**
* @param ActiveRecord|array $model
* @param array $attributes
* @return string
*/
private function getModelKey($model, $attributes)
{ {
if (count($attributes) > 1) { if (count($attributes) > 1) {
$key = array(); $key = array();
...@@ -228,7 +261,10 @@ class ActiveRelation extends ActiveQuery ...@@ -228,7 +261,10 @@ class ActiveRelation extends ActiveQuery
} }
} }
protected function filterByModels($models) /**
* @param array $models
*/
private function filterByModels($models)
{ {
$attributes = array_keys($this->link); $attributes = array_keys($this->link);
$values = array(); $values = array();
...@@ -255,7 +291,7 @@ class ActiveRelation extends ActiveQuery ...@@ -255,7 +291,7 @@ class ActiveRelation extends ActiveQuery
* @param ActiveRecord[] $primaryModels * @param ActiveRecord[] $primaryModels
* @return array * @return array
*/ */
protected function findPivotRows($primaryModels) private function findPivotRows($primaryModels)
{ {
if (empty($primaryModels)) { if (empty($primaryModels)) {
return array(); return array();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment