Abstract Class yii\db\BaseActiveRecord

继承yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\BaseObject
实现ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface, yii\db\ActiveRecordInterface
Uses Traitsyii\base\ArrayableTrait, yii\base\StaticInstanceTrait
子类yii\db\ActiveRecord
可用自版本2.0
源代码 https://github.com/yiisoft/yii2/blob/master/framework/db/BaseActiveRecord.php

ActiveRecord is the base class for classes representing relational data in terms of objects.

See yii\db\ActiveRecord for a concrete implementation.

公共属性

隐藏继承的属性

属性类型描述定义在
$activeValidators yii\validators\Validator[] The validators applicable to the current $scenario. yii\base\Model
$attributes array Attribute values (name => value). yii\base\Model
$behaviors yii\base\Behavior[] 附加到此组件的行为列表. yii\base\Component
$dirtyAttributes array The changed attribute values (name-value pairs) yii\db\BaseActiveRecord
$errors array Errors for all attributes or the specified attribute. yii\base\Model
$firstErrors array The first errors. yii\base\Model
$isNewRecord boolean Whether the record is new and should be inserted when calling save(). yii\db\BaseActiveRecord
$iterator ArrayIterator An iterator for traversing the items in the list. yii\base\Model
$oldAttributes array The old attribute values (name-value pairs) yii\db\BaseActiveRecord
$oldPrimaryKey mixed The old primary key value. yii\db\BaseActiveRecord
$primaryKey mixed The primary key value. yii\db\BaseActiveRecord
$relatedRecords array An array of related records indexed by relation names. yii\db\BaseActiveRecord
$scenario string The scenario that this model is in. yii\base\Model
$validators ArrayObject|yii\validators\Validator[] All the validators declared in the model. yii\base\Model

公共方法

隐藏继承的方法

方法描述定义在
__call() 调用不是类方法的指定的方法. yii\base\Component
__clone() 在通过克隆现有对象创建对象之后调用此方法. yii\base\Component
__construct() 构造函数. yii\base\BaseObject
__get() PHP getter magic method. yii\db\BaseActiveRecord
__isset() Checks if a property value is null. yii\db\BaseActiveRecord
__set() PHP setter magic method. yii\db\BaseActiveRecord
__unset() Sets a component property to be null. yii\db\BaseActiveRecord
activeAttributes() Returns the attribute names that are subject to validation in the current scenario. yii\base\Model
addError() Adds a new error to the specified attribute. yii\base\Model
addErrors() Adds a list of errors. yii\base\Model
afterDelete() This method is invoked after deleting a record. yii\db\BaseActiveRecord
afterFind() This method is called when the AR object is created and populated with the query result. yii\db\BaseActiveRecord
afterRefresh() This method is called when the AR object is refreshed. yii\db\BaseActiveRecord
afterSave() This method is called at the end of inserting or updating a record. yii\db\BaseActiveRecord
afterValidate() This method is invoked after validation ends. yii\base\Model
attachBehavior() 将行为附加到此组件. yii\base\Component
attachBehaviors() 将行为列表附加到组件. yii\base\Component
attributeHints() Returns the attribute hints. yii\base\Model
attributeLabels() Returns the attribute labels. yii\base\Model
attributes() Returns the list of all attribute names of the record. yii\db\ActiveRecordInterface
beforeDelete() This method is invoked before deleting a record. yii\db\BaseActiveRecord
beforeSave() This method is called at the beginning of inserting or updating a record. yii\db\BaseActiveRecord
beforeValidate() This method is invoked before validation starts. yii\base\Model
behaviors() 返回此组件应该具有的行为列表. yii\base\Component
canGetProperty() 返回一个值, 指示属性是否可读取. yii\db\BaseActiveRecord
canSetProperty() 返回一个值, 指示属性是否可设置. yii\db\BaseActiveRecord
className() 返回此类的完全限定名称. yii\base\BaseObject
clearErrors() Removes errors for all attributes or a single attribute. yii\base\Model
createValidators() Creates validator objects based on the validation rules specified in rules(). yii\base\Model
delete() Deletes the table row corresponding to this active record. yii\db\BaseActiveRecord
deleteAll() Deletes rows in the table using the provided conditions. yii\db\BaseActiveRecord
detachBehavior() 从组件中分离一个行为. yii\base\Component
detachBehaviors() 分离组件中的所有行为. yii\base\Component
ensureBehaviors() 确保在 behaviors() 中声明的行为已附加到此组件. yii\base\Component
equals() Returns a value indicating whether the given active record is the same as the current one. yii\db\BaseActiveRecord
extraFields() Returns the list of fields that can be expanded further and returned by toArray(). yii\db\BaseActiveRecord
fields() Returns the list of fields that should be returned by default by toArray() when no specific fields are specified. yii\db\BaseActiveRecord
find() Creates an yii\db\ActiveQueryInterface instance for query purpose. yii\db\ActiveRecordInterface
findAll() Returns a list of active record models that match the specified primary key value(s) or a set of column values. yii\db\BaseActiveRecord
findOne() Returns a single active record model instance by a primary key or an array of column values. yii\db\BaseActiveRecord
formName() Returns the form name that this model class should use. yii\base\Model
generateAttributeLabel() Generates a user friendly attribute label based on the give attribute name. yii\base\Model
getActiveValidators() Returns the validators applicable to the current $scenario. yii\base\Model
getAttribute() Returns the named attribute value. yii\db\BaseActiveRecord
getAttributeHint() Returns the text hint for the specified attribute. yii\db\BaseActiveRecord
getAttributeLabel() Returns the text label for the specified attribute. yii\db\BaseActiveRecord
getAttributes() Returns attribute values. yii\base\Model
getBehavior() 返回指定的行为对象. yii\base\Component
getBehaviors() 返回附加到此组件的所有行为. yii\base\Component
getDb() Returns the connection used by this AR class. yii\db\ActiveRecordInterface
getDirtyAttributes() Returns the attribute values that have been modified since they are loaded or saved most recently. yii\db\BaseActiveRecord
getErrorSummary() Returns the errors for all attributes as a one-dimensional array. yii\base\Model
getErrors() Returns the errors for all attributes or a single attribute. yii\base\Model
getFirstError() Returns the first error of the specified attribute. yii\base\Model
getFirstErrors() Returns the first error of every attribute in the model. yii\base\Model
getIsNewRecord() Returns a value indicating whether the current record is new. yii\db\BaseActiveRecord
getIterator() Returns an iterator for traversing the attributes in the model. yii\base\Model
getOldAttribute() Returns the old value of the named attribute. yii\db\BaseActiveRecord
getOldAttributes() Returns the old attribute values. yii\db\BaseActiveRecord
getOldPrimaryKey() Returns the old primary key value(s). yii\db\BaseActiveRecord
getPrimaryKey() Returns the primary key value(s). yii\db\BaseActiveRecord
getRelatedRecords() Returns all populated related records. yii\db\BaseActiveRecord
getRelation() Returns the relation object with the specified name. yii\db\BaseActiveRecord
getScenario() Returns the scenario that this model is used in. yii\base\Model
getValidators() Returns all the validators declared in rules(). yii\base\Model
hasAttribute() Returns a value indicating whether the model has an attribute with the specified name. yii\db\BaseActiveRecord
hasErrors() Returns a value indicating whether there is any validation error. yii\base\Model
hasEventHandlers() 返回一个值, 指示是否有任何处理程序附加到指定的事件. yii\base\Component
hasMany() Declares a has-many relation. yii\db\BaseActiveRecord
hasMethod() 返回一个值, 指示方法是否已定义. yii\base\Component
hasOne() Declares a has-one relation. yii\db\BaseActiveRecord
hasProperty() 返回一个值, 指示属性是否已定义. yii\base\Component
init() Initializes the object. yii\db\BaseActiveRecord
insert() Inserts the record into the database using the attribute values of this record. yii\db\ActiveRecordInterface
instance() Returns static class instance, which can be used to obtain meta information. yii\base\StaticInstanceTrait
instantiate() Creates an active record instance. yii\db\BaseActiveRecord
isAttributeActive() Returns a value indicating whether the attribute is active in the current scenario. yii\base\Model
isAttributeChanged() Returns a value indicating whether the named attribute has been changed. yii\db\BaseActiveRecord
isAttributeRequired() Returns a value indicating whether the attribute is required. yii\base\Model
isAttributeSafe() Returns a value indicating whether the attribute is safe for massive assignments. yii\base\Model
isPrimaryKey() Returns a value indicating whether the given set of attributes represents the primary key for this model. yii\db\BaseActiveRecord
isRelationPopulated() Check whether the named relation has been populated with records. yii\db\BaseActiveRecord
link() Establishes the relationship between two models. yii\db\BaseActiveRecord
load() Populates the model with input data. yii\base\Model
loadMultiple() Populates a set of models with the data from end user. yii\base\Model
markAttributeDirty() Marks an attribute dirty. yii\db\BaseActiveRecord
off() 从该组件分离现有的事件处理程序. yii\base\Component
offsetExists() Returns whether there is an element at the specified offset. yii\db\BaseActiveRecord
offsetGet() Returns the element at the specified offset. yii\base\Model
offsetSet() Sets the element at the specified offset. yii\base\Model
offsetUnset() Sets the element value at the specified offset to null. yii\db\BaseActiveRecord
on() 将事件处理程序附加到事件. yii\base\Component
onUnsafeAttribute() This method is invoked when an unsafe attribute is being massively assigned. yii\base\Model
optimisticLock() Returns the name of the column that stores the lock version for implementing optimistic locking. yii\db\BaseActiveRecord
populateRecord() Populates an active record object using a row of data from the database/storage. yii\db\BaseActiveRecord
populateRelation() Populates the named relation with the related records. yii\db\BaseActiveRecord
primaryKey() Returns the primary key name(s) for this AR class. yii\db\ActiveRecordInterface
refresh() Repopulates this active record with the latest data. yii\db\BaseActiveRecord
rules() Returns the validation rules for attributes. yii\base\Model
safeAttributes() Returns the attribute names that are safe to be massively assigned in the current scenario. yii\base\Model
save() Saves the current record. yii\db\BaseActiveRecord
scenarios() Returns a list of scenarios and the corresponding active attributes. yii\base\Model
setAttribute() Sets the named attribute value. yii\db\BaseActiveRecord
setAttributes() Sets the attribute values in a massive way. yii\base\Model
setIsNewRecord() Sets the value indicating whether the record is new. yii\db\BaseActiveRecord
setOldAttribute() Sets the old value of the named attribute. yii\db\BaseActiveRecord
setOldAttributes() Sets the old attribute values. yii\db\BaseActiveRecord
setScenario() Sets the scenario for the model. yii\base\Model
toArray() Converts the model into an array. yii\base\ArrayableTrait
trigger() 触发事件. yii\base\Component
unlink() Destroys the relationship between two models. yii\db\BaseActiveRecord
unlinkAll() Destroys the relationship in current model. yii\db\BaseActiveRecord
update() Saves the changes to this active record into the associated database table. yii\db\BaseActiveRecord
updateAll() Updates the whole table using the provided attribute values and conditions. yii\db\BaseActiveRecord
updateAllCounters() Updates the whole table using the provided counter changes and conditions. yii\db\BaseActiveRecord
updateAttributes() Updates the specified attributes. yii\db\BaseActiveRecord
updateCounters() Updates one or several counter columns for the current AR object. yii\db\BaseActiveRecord
validate() Performs the data validation. yii\base\Model
validateMultiple() Validates multiple models. yii\base\Model

受保护的方法

隐藏继承的方法

方法描述定义在
createRelationQuery() Creates a query instance for has-one or has-many relation. yii\db\BaseActiveRecord
extractFieldsFor() Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id". yii\base\ArrayableTrait
extractRootFields() Extracts the root field names from nested fields. yii\base\ArrayableTrait
findByCondition() Finds ActiveRecord instance(s) by the given condition. yii\db\BaseActiveRecord
refreshInternal() Repopulates this active record with the latest data from a newly fetched instance. yii\db\BaseActiveRecord
resolveFields() Determines which fields can be returned by toArray(). yii\base\ArrayableTrait
updateInternal() yii\db\BaseActiveRecord

事件

隐藏继承的事件

事件类型描述定义在
EVENT_AFTER_DELETE \yii\db\Event An event that is triggered after a record is deleted. yii\db\BaseActiveRecord
EVENT_AFTER_FIND \yii\db\Event An event that is triggered after the record is created and populated with query result. yii\db\BaseActiveRecord
EVENT_AFTER_INSERT yii\db\AfterSaveEvent An event that is triggered after a record is inserted. yii\db\BaseActiveRecord
EVENT_AFTER_REFRESH \yii\db\Event An event that is triggered after a record is refreshed. (available since version 2.0.8) yii\db\BaseActiveRecord
EVENT_AFTER_UPDATE yii\db\AfterSaveEvent An event that is triggered after a record is updated. yii\db\BaseActiveRecord
EVENT_AFTER_VALIDATE yii\base\Event An event raised at the end of validate() yii\base\Model
EVENT_BEFORE_DELETE yii\base\ModelEvent An event that is triggered before deleting a record. yii\db\BaseActiveRecord
EVENT_BEFORE_INSERT yii\base\ModelEvent An event that is triggered before inserting a record. yii\db\BaseActiveRecord
EVENT_BEFORE_UPDATE yii\base\ModelEvent An event that is triggered before updating a record. yii\db\BaseActiveRecord
EVENT_BEFORE_VALIDATE yii\base\ModelEvent An event raised at the beginning of validate(). yii\base\Model
EVENT_INIT \yii\db\Event An event that is triggered when the record is initialized via init(). yii\db\BaseActiveRecord

常量

隐藏继承的常量

常量描述定义在
SCENARIO_DEFAULT 'default' The name of the default scenario. yii\base\Model

属性详情

$dirtyAttributes public 只读 属性

The changed attribute values (name-value pairs)

public array getDirtyAttributes ( $names null )
$isNewRecord public 属性

Whether the record is new and should be inserted when calling save().

public boolean getIsNewRecord ( )
public void setIsNewRecord ( $value )
$oldAttributes public 属性

The old attribute values (name-value pairs)

public array getOldAttributes ( )
public void setOldAttributes ( $values )
$oldPrimaryKey public 只读 属性

The old primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned if the key value is null).

public mixed getOldPrimaryKey ( $asArray false )
$primaryKey public 只读 属性

The primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned if the key value is null).

public mixed getPrimaryKey ( $asArray false )
$relatedRecords public 只读 属性

An array of related records indexed by relation names.

方法详情

__get() public 方法

PHP getter magic method.

This method is overridden so that attributes and related objects can be accessed like properties.

参见 getAttribute().

public mixed __get ( $name )
$name string

Property name

return mixed

Property value

throws yii\base\InvalidArgumentException

if relation name is wrong

__isset() public 方法

Checks if a property value is null.

This method overrides the parent implementation by checking if the named attribute is null or not.

public boolean __isset ( $name )
$name string

The property name or the event name

return boolean

Whether the property value is null

__set() public 方法

PHP setter magic method.

This method is overridden so that AR attributes can be accessed like properties.

public void __set ( $name, $value )
$name string

Property name

$value mixed

Property value

__unset() public 方法

Sets a component property to be null.

This method overrides the parent implementation by clearing the specified attribute value.

public void __unset ( $name )
$name string

The property name or the event name

afterDelete() public 方法

This method is invoked after deleting a record.

The default implementation raises the EVENT_AFTER_DELETE event. You may override this method to do postprocessing after the record is deleted. Make sure you call the parent implementation so that the event is raised properly.

public void afterDelete ( )
afterFind() public 方法

This method is called when the AR object is created and populated with the query result.

The default implementation will trigger an EVENT_AFTER_FIND event. When overriding this method, make sure you call the parent implementation to ensure the event is triggered.

public void afterFind ( )
afterRefresh() public 方法 (可用自版本: 2.0.8)

This method is called when the AR object is refreshed.

The default implementation will trigger an EVENT_AFTER_REFRESH event. When overriding this method, make sure you call the parent implementation to ensure the event is triggered.

public void afterRefresh ( )
afterSave() public 方法

This method is called at the end of inserting or updating a record.

The default implementation will trigger an EVENT_AFTER_INSERT event when $insert is true, or an EVENT_AFTER_UPDATE event if $insert is false. The event class used is yii\db\AfterSaveEvent. When overriding this method, make sure you call the parent implementation so that the event is triggered.

public void afterSave ( $insert, $changedAttributes )
$insert boolean

Whether this method called while inserting a record. If false, it means the method is called while updating a record.

$changedAttributes array

The old values of attributes that had changed and were saved. You can use this parameter to take action based on the changes made for example send an email when the password had changed or implement audit trail that tracks all the changes. $changedAttributes gives you the old attribute values while the active record ($this) has already the new, updated values.

Note that no automatic type conversion performed by default. You may use yii\behaviors\AttributeTypecastBehavior to facilitate attribute typecasting. See http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.

beforeDelete() public 方法

This method is invoked before deleting a record.

The default implementation raises the EVENT_BEFORE_DELETE event. When overriding this method, make sure you call the parent implementation like the following:

public function beforeDelete()
{
    if (!parent::beforeDelete()) {
        return false;
    }

    // ...custom code here...
    return true;
}
public boolean beforeDelete ( )
return boolean

Whether the record should be deleted. Defaults to true.

beforeSave() public 方法

This method is called at the beginning of inserting or updating a record.

The default implementation will trigger an EVENT_BEFORE_INSERT event when $insert is true, or an EVENT_BEFORE_UPDATE event if $insert is false. When overriding this method, make sure you call the parent implementation like the following:

public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }

    // ...custom code here...
    return true;
}
public boolean beforeSave ( $insert )
$insert boolean

Whether this method called while inserting a record. If false, it means the method is called while updating a record.

return boolean

Whether the insertion or updating should continue. If false, the insertion or updating will be cancelled.

canGetProperty() public 方法

返回一个值, 指示属性是否可读取.

在以下情况下, 属性是可读的:

  • 该类具有与指定名称相关联的getter方法(在这种情况下, 属性名称不区分大小写);
  • 该类有一个具有指定名称的成员变量(当$checkVarstrue时);
  • 附加行为具有指定名称的可读属性(当$checkBehaviorstrue时).
public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

属性名称.

$checkVars boolean

是否将成员变量视为属性.

$checkBehaviors boolean

是否将行为的属性视为该组件的属性.

return boolean

属性是否可读取.

canSetProperty() public 方法

返回一个值, 指示属性是否可设置.

在以下情况下, 属性是可设置的:

  • 该类具有与指定名称相关联的setter方法(在这种情况下, 属性名称不区分大小写);
  • 该类有一个具有指定名称的成员变量(当$checkVarstrue时);
  • 附加行为具有指定名称的可写属性(当$checkBehaviorstrue时).
public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

属性名称.

$checkVars boolean

是否将成员变量视为属性.

$checkBehaviors boolean

是否将行为的属性视为该组件的属性.

return boolean

方法是否可设置.

createRelationQuery() protected 方法 (可用自版本: 2.0.12)

Creates a query instance for has-one or has-many relation.

参见:

protected yii\db\ActiveQueryInterface createRelationQuery ( $class, $link, $multiple )
$class string

The class name of the related record.

$link array

The primary-foreign key constraint.

$multiple boolean

Whether this query represents a relation to more than one record.

return yii\db\ActiveQueryInterface

The relational query object.

delete() public 方法

Deletes the table row corresponding to this active record.

This method performs the following steps in order:

  1. call beforeDelete(). If the method returns false, it will skip the rest of the steps;
  2. delete the record from the database;
  3. call afterDelete().

In the above step 1 and 3, events named EVENT_BEFORE_DELETE and EVENT_AFTER_DELETE will be raised by the corresponding methods.

public integer|false delete ( )
return integer|false

The number of rows deleted, or false if the deletion is unsuccessful for some reason. Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.

throws yii\db\StaleObjectException

if optimistic locking is enabled and the data being deleted is outdated.

throws yii\db\Exception

in case delete failed.

deleteAll() public static 方法

Deletes rows in the table using the provided conditions.

WARNING: If you do not specify any condition, this method will delete ALL rows in the table.

For example, to delete all customers whose status is 3:

Customer::deleteAll('status = 3');
public static integer deleteAll ( $condition null )
$condition string|array

The conditions that will be put in the WHERE part of the DELETE SQL. Please refer to yii\db\Query::where() on how to specify this parameter.

return integer

The number of rows deleted

throws yii\base\NotSupportedException

if not overridden.

equals() public 方法

Returns a value indicating whether the given active record is the same as the current one.

The comparison is made by comparing the table names and the primary key values of the two active records. If one of the records is new they are also considered not equal.

public boolean equals ( $record )
$record yii\db\ActiveRecordInterface

Record to compare to

return boolean

Whether the two active records refer to the same row in the same database table.

extraFields() public 方法

Returns the list of fields that can be expanded further and returned by toArray().

The default implementation returns the names of the relations that have been populated into this record.

This method is similar to fields() except that the list of fields returned by this method are not returned by default by toArray(). Only when field names to be expanded are explicitly specified when calling toArray(), will their values be exported.

The default implementation returns an empty array.

You may override this method to return a list of expandable fields based on some context information (e.g. the current application user).

public array extraFields ( )
return array

The list of expandable field names or field definitions. Please refer to fields() on the format of the return value.

fields() public 方法

Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.

The default implementation returns the names of the columns whose values have been populated into this record.

A field is a named element in the returned array by toArray().

This method should return an array of field names or field definitions. If the former, the field name will be treated as an object property name whose value will be used as the field value. If the latter, the array key should be the field name while the array value should be the corresponding field definition which can be either an object property name or a PHP callable returning the corresponding field value. The signature of the callable should be:

function ($model, $field) {
    // return field value
}

For example, the following code declares four fields:

  • email: the field name is the same as the property name email;
  • firstName and lastName: the field names are firstName and lastName, and their values are obtained from the first_name and last_name properties;
  • fullName: the field name is fullName. Its value is obtained by concatenating first_name and last_name.
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];

In this method, you may also want to return different lists of fields based on some context information. For example, depending on $scenario or the privilege of the current application user, you may return different sets of visible fields or filter out some fields.

The default implementation of this method returns attributes() indexed by the same attribute names.

public array fields ( )
return array

The list of field names or field definitions.

findAll() public static 方法

Returns a list of active record models that match the specified primary key value(s) or a set of column values.

The method accepts:

  • a scalar value (integer or string): query by a single primary key value and return an array containing the corresponding record (or an empty array if not found).
  • a non-associative array: query by a list of primary key values and return the corresponding records (or an empty array if none was found). Note that an empty condition will result in an empty result as it will be interpreted as a search for primary keys and not an empty WHERE condition.
  • an associative array of name-value pairs: query by a set of attribute values and return an array of records matching all of them (or an empty array if none was found). Note that ['id' => 1, 2] is treated as a non-associative array. Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limted to simple filter conditions.

This method will automatically call the all() method and return an array of ActiveRecord instances.

Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work. If you need to specify more complex conditions, use find() in combination with where() instead.

See the following code for usage examples:

// find the customers whose primary key value is 10
$customers = Customer::findAll(10);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();

If you need to pass user input to this method, make sure the input value is scalar or in case of array condition, make sure the array structure can not be changed from the outside:

// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static[] findAll ( $condition )
$condition mixed

Primary key value or a set of column values

return static[]

An array of ActiveRecord instances, or an empty array if nothing matches.

findByCondition() protected static 方法

Finds ActiveRecord instance(s) by the given condition.

This method is internally called by findOne() and findAll().

protected static yii\db\ActiveQueryInterface findByCondition ( $condition )
$condition mixed

Please refer to findOne() for the explanation of this parameter

return yii\db\ActiveQueryInterface

The newly created ActiveQuery instance.

throws yii\base\InvalidConfigException

if there is no primary key defined

findOne() public static 方法

Returns a single active record model instance by a primary key or an array of column values.

The method accepts:

  • a scalar value (integer or string): query by a single primary key value and return the corresponding record (or null if not found).
  • a non-associative array: query by a list of primary key values and return the first record (or null if not found).
  • an associative array of name-value pairs: query by a set of attribute values and return a single record matching all of them (or null if not found). Note that ['id' => 1, 2] is treated as a non-associative array. Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limited to simple filter conditions.

That this method will automatically call the one() method and return an ActiveRecord instance.

Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work. If you need to specify more complex conditions, use find() in combination with where() instead.

See the following code for usage examples:

// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);

// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findOne([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();

// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();

If you need to pass user input to this method, make sure the input value is scalar or in case of array condition, make sure the array structure can not be changed from the outside:

// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static|null findOne ( $condition )
$condition mixed

Primary key value or a set of column values

return static|null

ActiveRecord instance matching the condition, or null if nothing matches.

getAttribute() public 方法

Returns the named attribute value.

If this record is the result of a query and the attribute is not loaded, null will be returned.

参见 hasAttribute().

public mixed getAttribute ( $name )
$name string

The attribute name

return mixed

The attribute value. null if the attribute is not set or does not exist.

getAttributeHint() public 方法 (可用自版本: 2.0.4)

Returns the text hint for the specified attribute.

If the attribute looks like relatedModel.attribute, then the attribute will be received from the related model.

参见 attributeHints().

public string getAttributeHint ( $attribute )
$attribute string

The attribute name

return string

The attribute hint

getAttributeLabel() public 方法

Returns the text label for the specified attribute.

If the attribute looks like relatedModel.attribute, then the attribute will be received from the related model.

参见:

public string getAttributeLabel ( $attribute )
$attribute string

The attribute name

return string

The attribute label

getDirtyAttributes() public 方法

Returns the attribute values that have been modified since they are loaded or saved most recently.

The comparison of new and old values is made for identical values using ===.

public array getDirtyAttributes ( $names null )
$names string[]|null

The names of the attributes whose values may be returned if they are changed recently. If null, attributes() will be used.

return array

The changed attribute values (name-value pairs)

getIsNewRecord() public 方法

Returns a value indicating whether the current record is new.

public boolean getIsNewRecord ( )
return boolean

Whether the record is new and should be inserted when calling save().

getOldAttribute() public 方法

Returns the old value of the named attribute.

If this record is the result of a query and the attribute is not loaded, null will be returned.

参见 hasAttribute().

public mixed getOldAttribute ( $name )
$name string

The attribute name

return mixed

The old attribute value. null if the attribute is not loaded before or does not exist.

getOldAttributes() public 方法

Returns the old attribute values.

public array getOldAttributes ( )
return array

The old attribute values (name-value pairs)

getOldPrimaryKey() public 方法

Returns the old primary key value(s).

This refers to the primary key value that is populated into the record after executing a find method (e.g. find(), findOne()). The value remains unchanged even if the primary key attribute is manually assigned with a different value.

public mixed getOldPrimaryKey ( $asArray false )
$asArray boolean

Whether to return the primary key value as an array. If true, the return value will be an array with column name as key and column value as value. If this is false (default), a scalar value will be returned for non-composite primary key.

return mixed

The old primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned if the key value is null).

throws yii\db\Exception

if the AR model does not have a primary key

getPrimaryKey() public 方法

Returns the primary key value(s).

public mixed getPrimaryKey ( $asArray false )
$asArray boolean

Whether to return the primary key value as an array. If true, the return value will be an array with column names as keys and column values as values. Note that for composite primary keys, an array will always be returned regardless of this parameter value.

return mixed

The primary key value. An array (column name => column value) is returned if the primary key is composite or $asArray is true. A string is returned otherwise (null will be returned if the key value is null).

getRelatedRecords() public 方法

Returns all populated related records.

参见 getRelation().

public array getRelatedRecords ( )
return array

An array of related records indexed by relation names.

getRelation() public 方法

Returns the relation object with the specified name.

A relation is defined by a getter method which returns an yii\db\ActiveQueryInterface object. It can be declared in either the Active Record class itself or one of its behaviors.

public yii\db\ActiveQueryInterface|yii\db\ActiveQuery getRelation ( $name, $throwException true )
$name string

The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).

$throwException boolean

Whether to throw exception if the relation does not exist.

return yii\db\ActiveQueryInterface|yii\db\ActiveQuery

The relational query object. If the relation does not exist and $throwException is false, null will be returned.

throws yii\base\InvalidArgumentException

if the named relation does not exist.

hasAttribute() public 方法

Returns a value indicating whether the model has an attribute with the specified name.

public boolean hasAttribute ( $name )
$name string

The name of the attribute

return boolean

Whether the model has an attribute with the specified name.

hasMany() public 方法

Declares a has-many relation.

The declaration is returned in terms of a relational yii\db\ActiveQuery instance through which the related record can be queried and retrieved back.

A has-many relation means that there are multiple related records matching the criteria set by this relation, e.g., a customer has many orders.

For example, to declare the orders relation for Customer class, we can write the following code in the Customer class:

public function getOrders()
{
    return $this->hasMany(Order::className(), ['customer_id' => 'id']);
}

Note that in the above, the 'customer_id' key in the $link parameter refers to an attribute name in the related class Order, while the 'id' value refers to an attribute name in the current AR class.

Call methods declared in yii\db\ActiveQuery to further customize the relation.

public yii\db\ActiveQueryInterface hasMany ( $class, $link )
$class string

The class name of the related record

$link array

The primary-foreign key constraint. The keys of the array refer to the attributes of the record associated with the $class model, while the values of the array refer to the corresponding attributes in this AR class.

return yii\db\ActiveQueryInterface

The relational query object.

hasOne() public 方法

Declares a has-one relation.

The declaration is returned in terms of a relational yii\db\ActiveQuery instance through which the related record can be queried and retrieved back.

A has-one relation means that there is at most one related record matching the criteria set by this relation, e.g., a customer has one country.

For example, to declare the country relation for Customer class, we can write the following code in the Customer class:

public function getCountry()
{
    return $this->hasOne(Country::className(), ['id' => 'country_id']);
}

Note that in the above, the 'id' key in the $link parameter refers to an attribute name in the related class Country, while the 'country_id' value refers to an attribute name in the current AR class.

Call methods declared in yii\db\ActiveQuery to further customize the relation.

public yii\db\ActiveQueryInterface hasOne ( $class, $link )
$class string

The class name of the related record

$link array

The primary-foreign key constraint. The keys of the array refer to the attributes of the record associated with the $class model, while the values of the array refer to the corresponding attributes in this AR class.

return yii\db\ActiveQueryInterface

The relational query object.

init() public 方法

Initializes the object.

This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event.

public void init ( )
instantiate() public static 方法

Creates an active record instance.

This method is called together with populateRecord() by yii\db\ActiveQuery. It is not meant to be used for creating new records directly.

You may override this method if the instance being created depends on the row data to be populated into the record. For example, by creating a record based on the value of a column, you may implement the so-called single-table inheritance mapping.

public static static instantiate ( $row )
$row array

Row data to be populated into the record.

return static

The newly created active record

isAttributeChanged() public 方法

Returns a value indicating whether the named attribute has been changed.

public boolean isAttributeChanged ( $name, $identical true )
$name string

The name of the attribute.

$identical boolean

Whether the comparison of new and old value is made for identical values using ===, defaults to true. Otherwise == is used for comparison. This parameter is available since version 2.0.4.

return boolean

Whether the attribute has been changed

isPrimaryKey() public static 方法

Returns a value indicating whether the given set of attributes represents the primary key for this model.

public static boolean isPrimaryKey ( $keys )
$keys array

The set of attributes to check

return boolean

Whether the given set of attributes represents the primary key for this model

isRelationPopulated() public 方法

Check whether the named relation has been populated with records.

参见 getRelation().

public boolean isRelationPopulated ( $name )
$name string

The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).

return boolean

Whether relation has been populated with records.

link() public 方法

Establishes the relationship between two models.

The relationship is established by setting the foreign key value(s) in one model to be the corresponding primary key value(s) in the other model. The model with the foreign key will be saved into database without performing validation.

If the relationship involves a junction table, a new row will be inserted into the junction table which contains the primary key values from both models.

Note that this method requires that the primary key value is not null.

public void link ( $name, $model, $extraColumns = [] )
$name string

The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.

$model yii\db\ActiveRecordInterface

The model to be linked with the current one.

$extraColumns array

Additional column values to be saved into the junction table. This parameter is only meaningful for a relationship involving a junction table (i.e., a relation set with yii\db\ActiveRelationTrait::via() or yii\db\ActiveQuery::viaTable().)

throws yii\base\InvalidCallException

if the method is unable to link two models.

markAttributeDirty() public 方法

Marks an attribute dirty.

This method may be called to force updating a record when calling update(), even if there is no change being made to the record.

public void markAttributeDirty ( $name )
$name string

The attribute name

offsetExists() public 方法

Returns whether there is an element at the specified offset.

This method is required by the interface ArrayAccess.

public boolean offsetExists ( $offset )
$offset mixed

The offset to check on

return boolean

Whether there is an element at the specified offset.

offsetUnset() public 方法

Sets the element value at the specified offset to null.

This method is required by the SPL interface ArrayAccess. It is implicitly called when you use something like unset($model[$offset]).

public void offsetUnset ( $offset )
$offset mixed

The offset to unset element

optimisticLock() public 方法

Returns the name of the column that stores the lock version for implementing optimistic locking.

Optimistic locking allows multiple users to access the same record for edits and avoids potential conflicts. In case when a user attempts to save the record upon some staled data (because another user has modified the data), a yii\db\StaleObjectException exception will be thrown, and the update or deletion is skipped.

Optimistic locking is only supported by update() and delete().

To use Optimistic locking:

  1. Create a column to store the version number of each row. The column type should be BIGINT DEFAULT 0. Override this method to return the name of this column.
  2. Ensure the version value is submitted and loaded to your model before any update or delete. Or add OptimisticLockBehavior to your model class in order to automate the process.
  3. In the Web form that collects the user input, add a hidden field that stores the lock version of the recording being updated.
  4. In the controller action that does the data updating, try to catch the yii\db\StaleObjectException and implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
public string optimisticLock ( )
return string

The column name that stores the lock version of a table row. If null is returned (default implemented), optimistic locking will not be supported.

populateRecord() public static 方法

Populates an active record object using a row of data from the database/storage.

This is an internal method meant to be called to create active record objects after fetching data from the database. It is mainly used by yii\db\ActiveQuery to populate the query results into active records.

When calling this method manually you should call afterFind() on the created record to trigger the afterFind Event.

public static void populateRecord ( $record, $row )
$record yii\db\BaseActiveRecord

The record to be populated. In most cases this will be an instance created by instantiate() beforehand.

$row array

Attribute values (name => value)

populateRelation() public 方法

Populates the named relation with the related records.

Note that this method does not check if the relation exists or not.

参见 getRelation().

public void populateRelation ( $name, $records )
$name string

The relation name, e.g. orders for a relation defined via getOrders() method (case-sensitive).

$records yii\db\ActiveRecordInterface|array|null

The related records to be populated into the relation.

refresh() public 方法

Repopulates this active record with the latest data.

If the refresh is successful, an EVENT_AFTER_REFRESH event will be triggered. This event is available since version 2.0.8.

public boolean refresh ( )
return boolean

Whether the row still exists in the database. If true, the latest data will be populated to this active record. Otherwise, this record will remain unchanged.

refreshInternal() protected 方法 (可用自版本: 2.0.13)

Repopulates this active record with the latest data from a newly fetched instance.

参见 refresh().

protected boolean refreshInternal ( $record )
$record yii\db\BaseActiveRecord

The record to take attributes from.

return boolean

Whether refresh was successful.

save() public 方法

Saves the current record.

This method will call insert() when $isNewRecord is true, or update() when $isNewRecord is false.

For example, to save a customer record:

$customer = new Customer; // or $customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->save();
public boolean save ( $runValidation true, $attributeNames null )
$runValidation boolean

Whether to perform validation (calling validate()) before saving the record. Defaults to true. If the validation fails, the record will not be saved to the database and this method will return false.

$attributeNames array

List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.

return boolean

Whether the saving succeeded (i.e. no validation errors occurred).

setAttribute() public 方法

Sets the named attribute value.

参见 hasAttribute().

public void setAttribute ( $name, $value )
$name string

The attribute name

$value mixed

The attribute value.

throws yii\base\InvalidArgumentException

if the named attribute does not exist.

setIsNewRecord() public 方法

Sets the value indicating whether the record is new.

参见 getIsNewRecord().

public void setIsNewRecord ( $value )
$value boolean

Whether the record is new and should be inserted when calling save().

setOldAttribute() public 方法

Sets the old value of the named attribute.

参见 hasAttribute().

public void setOldAttribute ( $name, $value )
$name string

The attribute name

$value mixed

The old attribute value.

throws yii\base\InvalidArgumentException

if the named attribute does not exist.

setOldAttributes() public 方法

Sets the old attribute values.

All existing old attribute values will be discarded.

public void setOldAttributes ( $values )
$values array|null

Old attribute values to be set. If set to null this record is considered to be new.

unlink() public 方法

Destroys the relationship between two models.

The model with the foreign key of the relationship will be deleted if $delete is true. Otherwise, the foreign key will be set null and the model will be saved without validation.

public void unlink ( $name, $model, $delete false )
$name string

The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.

$model yii\db\ActiveRecordInterface

The model to be unlinked from the current one. You have to make sure that the model is really related with the current model as this method does not check this.

$delete boolean

Whether to delete the model that contains the foreign key. If false, the model's foreign key will be set null and saved. If true, the model containing the foreign key will be deleted.

throws yii\base\InvalidCallException

if the models cannot be unlinked

unlinkAll() public 方法

Destroys the relationship in current model.

The model with the foreign key of the relationship will be deleted if $delete is true. Otherwise, the foreign key will be set null and the model will be saved without validation.

Note that to destroy the relationship without removing records make sure your keys can be set to null

public void unlinkAll ( $name, $delete false )
$name string

The case sensitive name of the relationship, e.g. orders for a relation defined via getOrders() method.

$delete boolean

Whether to delete the model that contains the foreign key.

Note that the deletion will be performed using deleteAll(), which will not trigger any events on the related models. If you need EVENT_BEFORE_DELETE or EVENT_AFTER_DELETE to be triggered, you need to find the models first and then call delete() on each of them.

update() public 方法

Saves the changes to this active record into the associated database table.

This method performs the following steps in order:

  1. call beforeValidate() when $runValidation is true. If beforeValidate() returns false, the rest of the steps will be skipped;
  2. call afterValidate() when $runValidation is true. If validation failed, the rest of the steps will be skipped;
  3. call beforeSave(). If beforeSave() returns false, the rest of the steps will be skipped;
  4. save the record into database. If this fails, it will skip the rest of the steps;
  5. call afterSave();

In the above step 1, 2, 3 and 5, events EVENT_BEFORE_VALIDATE, EVENT_AFTER_VALIDATE, EVENT_BEFORE_UPDATE, and EVENT_AFTER_UPDATE will be raised by the corresponding methods.

Only the changed attribute values will be saved into database.

For example, to update a customer record:

$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();

Note that it is possible the update does not affect any row in the table. In this case, this method will return 0. For this reason, you should use the following code to check if update() is successful or not:

if ($customer->update() !== false) {
    // update successful
} else {
    // update failed
}
public integer|false update ( $runValidation true, $attributeNames null )
$runValidation boolean

Whether to perform validation (calling validate()) before saving the record. Defaults to true. If the validation fails, the record will not be saved to the database and this method will return false.

$attributeNames array

List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved.

return integer|false

The number of rows affected, or false if validation fails or beforeSave() stops the updating process.

throws yii\db\StaleObjectException

if optimistic locking is enabled and the data being updated is outdated.

throws yii\db\Exception

in case update failed.

updateAll() public static 方法

Updates the whole table using the provided attribute values and conditions.

For example, to change the status to be 1 for all customers whose status is 2:

Customer::updateAll(['status' => 1], 'status = 2');
public static integer updateAll ( $attributes, $condition '' )
$attributes array

Attribute values (name-value pairs) to be saved into the table

$condition string|array

The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to yii\db\Query::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\base\NotSupportedException

if not overridden

updateAllCounters() public static 方法

Updates the whole table using the provided counter changes and conditions.

For example, to increment all customers' age by 1,

Customer::updateAllCounters(['age' => 1]);
public static integer updateAllCounters ( $counters, $condition '' )
$counters array

The counters to be updated (attribute name => increment value). Use negative values if you want to decrement the counters.

$condition string|array

The conditions that will be put in the WHERE part of the UPDATE SQL. Please refer to yii\db\Query::where() on how to specify this parameter.

return integer

The number of rows updated

throws yii\base\NotSupportedException

if not overrided

updateAttributes() public 方法

Updates the specified attributes.

This method is a shortcut to update() when data validation is not needed and only a small set attributes need to be updated.

You may specify the attributes to be updated as name list or name-value pairs. If the latter, the corresponding attribute values will be modified accordingly. The method will then save the specified attributes into database.

Note that this method will not perform data validation and will not trigger events.

public integer updateAttributes ( $attributes )
$attributes array

The attributes (names or name-value pairs) to be updated

return integer

The number of rows affected.

updateCounters() public 方法

Updates one or several counter columns for the current AR object.

Note that this method differs from updateAllCounters() in that it only saves counters for the current AR object.

An example usage is as follows:

$post = Post::findOne($id);
$post->updateCounters(['view_count' => 1]);

参见 updateAllCounters().

public boolean updateCounters ( $counters )
$counters array

The counters to be updated (attribute name => increment value) Use negative values if you want to decrement the counters.

return boolean

Whether the saving is successful

updateInternal() protected 方法

参见 update().

protected integer|false updateInternal ( $attributes null )
$attributes array

Attributes to update

return integer|false

The number of rows affected, or false if beforeSave() stops the updating process.

throws yii\db\StaleObjectException

事件详情

EVENT_AFTER_DELETE 事件类型 \yii\db\Event

An event that is triggered after a record is deleted.

EVENT_AFTER_FIND 事件类型 \yii\db\Event

An event that is triggered after the record is created and populated with query result.

EVENT_AFTER_INSERT 事件类型 yii\db\AfterSaveEvent

An event that is triggered after a record is inserted.

EVENT_AFTER_REFRESH 事件类型 \yii\db\Event (可用自版本: 2.0.8)

An event that is triggered after a record is refreshed.

EVENT_AFTER_UPDATE 事件类型 yii\db\AfterSaveEvent

An event that is triggered after a record is updated.

EVENT_BEFORE_DELETE 事件类型 yii\base\ModelEvent

An event that is triggered before deleting a record. You may set yii\base\ModelEvent::$isValid to be false to stop the deletion.

EVENT_BEFORE_INSERT 事件类型 yii\base\ModelEvent

An event that is triggered before inserting a record. You may set yii\base\ModelEvent::$isValid to be false to stop the insertion.

EVENT_BEFORE_UPDATE 事件类型 yii\base\ModelEvent

An event that is triggered before updating a record. You may set yii\base\ModelEvent::$isValid to be false to stop the update.

EVENT_INIT 事件类型 \yii\db\Event

An event that is triggered when the record is initialized via init().