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
/**
* ActiveFinder class file.
* ActiveQuery class file.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
......@@ -13,10 +13,41 @@ namespace yii\db;
use yii\db\Connection;
use yii\db\Command;
use yii\db\QueryBuilder;
use yii\base\VectorIterator;
use yii\db\Expression;
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
{
/**
......@@ -28,7 +59,7 @@ class ActiveQuery extends Query
*/
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()]].
*/
public $indexBy;
......@@ -47,6 +78,14 @@ class ActiveQuery extends Query
*/
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)
{
if (method_exists($this->modelClass, $name)) {
......@@ -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.
* @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()
{
......@@ -113,8 +152,8 @@ class ActiveQuery extends Query
}
/**
* Executes query and returns if matching row exists in the table.
* @return bool if row exists in the table.
* Returns a value indicating whether the query result contains any row of data.
* @return boolean whether the query result contains any row of data.
*/
public function exists()
{
......@@ -141,14 +180,7 @@ class ActiveQuery extends Query
$this->from = array($tableName);
}
if (!empty($this->scopes)) {
foreach ($this->scopes as $name => $config) {
if (is_integer($name)) {
$modelClass::$config($this);
} else {
array_unshift($config, $this);
call_user_func_array(array($modelClass, $name), $config);
}
}
$this->applyScopes($this->scopes);
}
/** @var $qb QueryBuilder */
$qb = $db->getQueryBuilder();
......@@ -157,12 +189,39 @@ class ActiveQuery extends Query
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)
{
$this->asArray = $value;
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()
{
$this->with = func_get_args();
......@@ -173,13 +232,39 @@ class ActiveQuery extends Query
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)
{
$this->indexBy = $column;
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();
if (isset($this->scopes[0]) && is_array($this->scopes[0])) {
......@@ -189,7 +274,7 @@ class ActiveQuery extends Query
return $this;
}
protected function createModels($rows)
private function createModels($rows)
{
$models = array();
if ($this->asArray) {
......@@ -216,7 +301,7 @@ class ActiveQuery extends Query
return $models;
}
protected function populateRelations(&$models, $with)
private function populateRelations(&$models, $with)
{
$primaryModel = new $this->modelClass;
$relations = $this->normalizeRelations($primaryModel, $with);
......@@ -233,9 +318,8 @@ class ActiveQuery extends Query
* @param ActiveRecord $model
* @param array $with
* @return ActiveRelation[]
* @throws \yii\db\Exception
*/
protected function normalizeRelations($model, $with)
private function normalizeRelations($model, $with)
{
$relations = array();
foreach ($with as $name => $callback) {
......@@ -268,4 +352,17 @@ class ActiveQuery extends Query
}
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;
use yii\db\Connection;
use yii\db\Command;
use yii\base\BadParamException;
/**
* It is used in three scenarios:
* - eager loading: User::find()->with('posts')->all();
* - lazy loading: $user->posts;
* - lazy loading with query options: $user->posts()->where('status=1')->get();
* ActiveRelation represents a relation between two Active Record classes.
*
* ActiveRelation instances are usually created by calling [[ActiveRecord::hasOne()]] and
* [[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>
* @since 2.0
......@@ -42,15 +49,17 @@ class ActiveRelation extends ActiveQuery
*/
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;
/**
* @param string $relationName
* @param callback $callback
* @return ActiveRelation
* @throws Exception
* Specifies the relation associated with the pivot table.
* @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
* @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 the relation object itself.
*/
public function via($relationName, $callback = null)
{
......@@ -63,9 +72,13 @@ class ActiveRelation extends ActiveQuery
}
/**
* @param string $tableName
* @param array $link
* @param callback $callback
* Specifies the pivot table.
* @param string $tableName the name of the pivot table.
* @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
*/
public function viaTable($tableName, $link, $callback = null)
......@@ -118,10 +131,18 @@ class ActiveRelation extends ActiveQuery
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)
{
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) {
......@@ -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();
$linkKeys = array_keys($link);
......@@ -214,7 +242,12 @@ class ActiveRelation extends ActiveQuery
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) {
$key = array();
......@@ -228,7 +261,10 @@ class ActiveRelation extends ActiveQuery
}
}
protected function filterByModels($models)
/**
* @param array $models
*/
private function filterByModels($models)
{
$attributes = array_keys($this->link);
$values = array();
......@@ -255,7 +291,7 @@ class ActiveRelation extends ActiveQuery
* @param ActiveRecord[] $primaryModels
* @return array
*/
protected function findPivotRows($primaryModels)
private function findPivotRows($primaryModels)
{
if (empty($primaryModels)) {
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