没有命名空间的类 yii yii\base yii\behaviors yii\caching yii\captcha yii\console yii\console\controllers yii\console\widgets yii\data yii\db yii\db\conditions yii\db\cubrid yii\db\cubrid\conditions yii\db\mssql yii\db\mssql\conditions yii\db\mysql yii\db\oci yii\db\oci\conditions yii\db\pgsql yii\db\sqlite yii\db\sqlite\conditions yii\di yii\filters yii\filters\auth yii\grid yii\helpers yii\i18n yii\log yii\mail yii\mutex yii\rbac yii\rest yii\test yii\validators yii\web yii\widgets

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
使用 Traitsyii\base\ArrayableTrait, yii\base\StaticInstanceTrait
子类yii\db\ActiveRecord
可用版本自2.0
源码 https://github.com/yiichina/yii2/blob/api/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[] List of behaviors attached to this component 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() Calls the named method which is not a class method. yii\base\Component
__clone() This method is called after the object is created by cloning an existing one. yii\base\Component
__construct() Constructor. 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() Attaches a behavior to this component. yii\base\Component
attachBehaviors() Attaches a list of behaviors to the component. yii\base\Component
attributeHints() Returns the attribute hints. yii\base\Model
attributeLabels() Returns the attribute labels. yii\base\Model
attributes() 返回记录的所有属性列表名称。 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() Returns a list of behaviors that this component should behave as. yii\base\Component
canGetProperty() Returns a value indicating whether a property can be read. yii\db\BaseActiveRecord
canSetProperty() Returns a value indicating whether a property can be set. yii\db\BaseActiveRecord
className() Returns the fully qualified name of this class. 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() Detaches a behavior from the component. yii\base\Component
detachBehaviors() Detaches all behaviors from the component. yii\base\Component
ensureBehaviors() Makes sure that the behaviors declared in behaviors() are attached to this component. 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() 创建用来查询的 yii\db\ActiveQueryInterface 实例。 yii\db\ActiveRecordInterface
findAll() 返回与指定的主键值或一组列值匹配的活动记录模型的列表。 yii\db\BaseActiveRecord
findOne() 通过主键或列值数组返回单个活动记录模型实例。 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() Returns the named behavior object. yii\base\Component
getBehaviors() Returns all behaviors attached to this component. yii\base\Component
getDb() 返回此 AR 类使用的连接。 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() Returns a value indicating whether there is any handler attached to the named event. yii\base\Component
hasMany() Declares a has-many relation. yii\db\BaseActiveRecord
hasMethod() Returns a value indicating whether a method is defined. yii\base\Component
hasOne() Declares a has-one relation. yii\db\BaseActiveRecord
hasProperty() Returns a value indicating whether a property is defined for this component. yii\base\Component
init() Initializes the object. yii\db\BaseActiveRecord
insert() 使用此记录的属性值将记录插入数据库。 yii\db\ActiveRecordInterface
instance() 返回静态类实例,该实例可用于获取 meta 信息 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() Detaches an existing event handler from this component. 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() Attaches an event handler to an event. 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() 返回此 AR 类的主键 name(s) 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() Triggers an event. 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

Events

隐藏继承的事件

事件类型描述被定义在
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. (自版本 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 公共 只读 属性

The changed attribute values (name-value pairs)

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

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

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

The old attribute values (name-value pairs)

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

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 公共 只读 属性

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 公共 只读 属性

An array of related records indexed by relation names.

方法详情

__get() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法 (自版本 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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

Returns a value indicating whether a property can be read.

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).
public boolean canGetProperty($name, $checkVars true, $checkBehaviors true)
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be read

canSetProperty() 公共 方法

Returns a value indicating whether a property can be set.

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).
public boolean canSetProperty($name, $checkVars true, $checkBehaviors true)
$name string

The property name

$checkVars boolean

Whether to treat member variables as properties

$checkBehaviors boolean

Whether to treat behaviors' properties as properties of this component

return boolean

Whether the property can be written

createRelationQuery() 受保护 方法 (自版本 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() 公共 方法

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() 公共 静态 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 静态 方法

返回与指定的主键值或一组列值匹配的活动记录模型的列表。

The method accepts:

  • 标量值(integer 或 string):通过单个主键值进行查询并返回包含相应记录的数组 (如果未找到则返回空数组)。
  • 非关联数组:按主键值列表查询并返回相应记录 (如果没有找到则返回空数组)。 注意,空条件将导致空结果, 因为它将被解释为搜索结果主键而不是空的 WHERE 条件。
  • 一个键值对关联数组:通过一组属性值进行查询, 并返回所有属性值匹配的记录数组(如果没有找到则返回空数组) 请注意,['id' => 1, 2] 被视为非关联数组。 列名仅限于 SQL DBMS 的当前记录表列,否则将过滤以限制为简单的过滤条件。

此方法将自动调用 all() 方法并返回 ActiveRecord 实例的数组。

Note:因为只是一种简单的方法,所以使用更复杂的条件,比如 ['!=', 'id', 1] 将不起作用。 如果需要指定更复杂的条件,请将 find()where() 组合使用。

有关于用法示例,请参阅以下代码:

// 找到主键值为 10 的客户
$customers = Customer::findAll(10);

// 上面的代码相当于:
$customers = Customer::find()->where(['id' => 10])->all();

// 找到主键值为 10,11 或 12 的客户。
$customers = Customer::findAll([10, 11, 12]);

// 上面的代码相当于:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

// 找到年龄为 30 岁且状态为 1 的客户
$customers = Customer::findAll(['age' => 30, 'status' => 1]);

// 上面的代码相当于:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();

如果需要将用户输入传递给此方法,在输入值是标量或在数组条件情况下, 确保无法从外部更改数组数组结构:

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

// 显式指定要搜索的列,在此处传递标量或数组将始终导致查找单个记录
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// 不要使用以下代码!可以通过任意列值注入数组条件来过滤!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static[] findAll($condition)
$condition mixed

主键值或一组列值

return static[]

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

findByCondition() 受保护 静态 方法

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() 公共 静态 方法

通过主键或列值数组返回单个活动记录模型实例。

该方法接受:

  • 标量值(integer 或 string):按单个主键值查询并返回记录 (如果未找到就返回 null)。
  • 一个非关联数组:按主键值列表查询并返回第一条记录 (如果未找到就返回 null)。
  • 一个键值对:通过一组属性值进行查询,并返回匹配所有属性值的单个记录(如果未找到就返回 null)。 注意,['id' => 1, 2] 被视为非关联数组。 列名仅限于 SQL DBMS 的当前记录列表,或者过滤为限制为简单的过滤条件。

该方法将自动调用 one() 方法并且返回 ActiveRecord 实例。

Note: 因为只是一种简单的方法,所以使用更复杂的条件,比如 ['!=', 'id', 1] 将不起作用。 如果需要指定更复杂的条件,请将 find()where() 组合使用。

有关用法的示例,请参阅以下代码:

// 找到主键值为 10 的单个客户
$customer = Customer::findOne(10);

// 上面的代码相当于:
$customer = Customer::find()->where(['id' => 10])->one();

// 找到主键值为 10,11 或 12 的客户。
$customers = Customer::findOne([10, 11, 12]);

// 上面的代码相当于:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();

// 找到第一个年龄为 30 岁且状态为 1 的客户
$customer = Customer::findOne(['age' => 30, 'status' => 1]);

// 上面的代码相当于:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();

如果需要将用户输入传递给此方法,在输入值是标量或在数组条件情况下, 确保无法从外部更改数组结构:

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

// 显示指定要搜索的列,在此处传递标量或数组将始终导致查询单个记录
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// 不要使用以下代码!可以通过任意列值注入数组条件来过滤!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static|null findOne($condition)
$condition mixed

主键值或一组列值。

return static|null

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

getAttribute() 公共 方法

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() 公共 方法 (自版本 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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

Returns the old attribute values.

public array getOldAttributes()
return array

The old attribute values (name-value pairs)

getOldPrimaryKey() 公共 方法

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() 公共 方法

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() 公共 方法

Returns all populated related records.

参见 getRelation().

public array getRelatedRecords()
return array

An array of related records indexed by relation names.

getRelation() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 静态 方法

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() 公共 方法

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() 公共 静态 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 静态 方法

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() 公共 方法

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() 公共 方法

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() 受保护 方法 (自版本 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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 方法

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() 公共 静态 方法

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() 公共 静态 方法

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() 公共 方法

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() 公共 方法

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() 受保护 方法

参见 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 event of type \yii\db\Event

An event that is triggered after a record is deleted.

EVENT_AFTER_FIND event of type \yii\db\Event

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

EVENT_AFTER_INSERT event of type yii\db\AfterSaveEvent

An event that is triggered after a record is inserted.

EVENT_AFTER_REFRESH event of type \yii\db\Event ( 自版本 2.0.8 可用)

An event that is triggered after a record is refreshed.

EVENT_AFTER_UPDATE event of type yii\db\AfterSaveEvent

An event that is triggered after a record is updated.

EVENT_BEFORE_DELETE event of type 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 event of type 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 event of type 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 event of type \yii\db\Event

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