HumHub Documentation (unofficial)

Live extends ActiveRecord
in package

This is the model class for table "live".

Table of Contents

Constants

EVENT_AFTER_DELETE  = 'afterDelete'
EVENT_AFTER_FIND  = 'afterFind'
EVENT_AFTER_INSERT  = 'afterInsert'
EVENT_AFTER_REFRESH  = 'afterRefresh'
EVENT_AFTER_UPDATE  = 'afterUpdate'
EVENT_AFTER_VALIDATE  = 'afterValidate'
EVENT_APPEND_RULES  = 'appendRules'
EVENT_BEFORE_DELETE  = 'beforeDelete'
EVENT_BEFORE_INSERT  = 'beforeInsert'
EVENT_BEFORE_UPDATE  = 'beforeUpdate'
EVENT_BEFORE_VALIDATE  = 'beforeValidate'
EVENT_INIT  = 'init'
OP_ALL  = 0x7
All three operations: insert, update, delete.
OP_DELETE  = 0x4
The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
OP_INSERT  = 0x1
The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
OP_UPDATE  = 0x2
The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.
SCENARIO_DEFAULT  = 'default'
The name of the default scenario.

Properties

$activeValidators  : array<string|int, Validator>
$attributes  : array<string|int, mixed>
$behaviors  : array<string|int, Behavior>
$contentcontainer  : Contentcontainer
$contentcontainer_id  : int
$created_at  : int
$createdBy  : User
$dirtyAttributes  : array<string|int, mixed>
$errors  : array<string|int, mixed>
$fileManager  : FileManager
$fileManagerEnableHistory  : bool
$firstErrors  : array<string|int, mixed>
$id  : int
$isNewRecord  : bool
$oldAttributes  : array<string|int, mixed>
$oldPrimaryKey  : mixed
$primaryKey  : mixed
$relatedRecords  : array<string|int, mixed>
$scenario  : string
$serialized_data  : string
$updatedBy  : User
$validators  : ArrayObject|array<string|int, Validator>
$visibility  : int
$_attributes  : array<string|int, mixed>
$_behaviors  : array<string|int, Behavior>|null
$_errors  : array<string|int, mixed>
$_events  : array<string|int, mixed>
$_eventWildcards  : array<string|int, mixed>
$_fileManager  : FileManager
$_instances  : array<string|int, static>
$_oldAttributes  : array<string|int, mixed>|null
$_related  : array<string|int, mixed>
$_relationsDependencies  : array<string|int, mixed>
$_scenario  : string
$_validators  : ArrayObject

Methods

__call()  : mixed
Calls the named method which is not a class method.
__clone()  : mixed
This method is called after the object is created by cloning an existing one.
__construct()  : mixed
Constructor.
__get()  : mixed
PHP getter magic method.
__isset()  : bool
Checks if a property value is null.
__serialize()  : array<string|int, mixed>
Serializes attributes and oldAttributes of this record.
__set()  : mixed
PHP setter magic method.
__unserialize()  : mixed
Unserializes the given string, calls the init() function and sets the attributes and oldAttributes.
__unset()  : mixed
Sets a component property to be null.
activeAttributes()  : array<string|int, string>
Returns the attribute names that are subject to validation in the current scenario.
addError()  : mixed
Adds a new error to the specified attribute.
addErrors()  : mixed
Adds a list of errors.
afterDelete()  : mixed
This method is invoked after deleting a record.
afterFind()  : mixed
This method is called when the AR object is created and populated with the query result.
afterRefresh()  : mixed
This method is called when the AR object is refreshed.
afterSave()  : mixed
This method is called at the end of inserting or updating a record.
afterValidate()  : mixed
This method is invoked after validation ends.
attachBehavior()  : Behavior
Attaches a behavior to this component.
attachBehaviors()  : mixed
Attaches a list of behaviors to the component.
attributeHints()  : array<string|int, mixed>
Returns the attribute hints.
attributeLabels()  : array<string|int, mixed>
Returns the attribute labels.
attributes()  : array<string|int, mixed>
Returns the list of all attribute names of the model.
beforeDelete()  : bool
This method is invoked before deleting a record.
beforeSave()  : bool
This method is called at the beginning of inserting or updating a record.
beforeValidate()  : bool
This method is invoked before validation starts.
behaviors()  : array<string|int, mixed>
Returns a list of behaviors that this component should behave as.
canGetProperty()  : bool
Returns a value indicating whether a property can be read.
canSetOldAttribute()  : bool
Returns if the old named attribute can be set.
canSetProperty()  : bool
Returns a value indicating whether a property can be set.
className()  : string
Returns the fully qualified name of this class.
clearErrors()  : mixed
Removes errors for all attributes or a single attribute.
createValidators()  : ArrayObject
Creates validator objects based on the validation rules specified in [[rules()]].
delete()  : int|false
Deletes the table row corresponding to this active record.
deleteAll()  : int
Deletes rows in the table using the provided conditions.
detachBehavior()  : Behavior|null
Detaches a behavior from the component.
detachBehaviors()  : mixed
Detaches all behaviors from the component.
ensureBehaviors()  : mixed
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
equals()  : bool
Returns a value indicating whether the given active record is the same as the current one.
extraFields()  : array<string|int, mixed>
Returns the list of additional fields that can be returned by [[toArray()]] in addition to those listed in [[fields()]].
fields()  : array<string|int, mixed>
Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
find()  : ActiveQuery
Creates an [[ActiveQueryInterface]] instance for query purpose.
findAll()  : array<string|int, static>
Returns a list of active record models that match the specified primary key value(s) or a set of column values.
findBySql()  : ActiveQuery
Creates an [[ActiveQuery]] instance with a given SQL statement.
findOne()  : static|null
Returns a single active record model instance by a primary key or an array of column values.
formName()  : string
Returns the form name that this model class should use.
generateAttributeLabel()  : string
Generates a user friendly attribute label based on the give attribute name.
getActiveValidators()  : array<string|int, Validator>
Returns the validators applicable to the current [[scenario]].
getAttribute()  : mixed
Returns the named attribute value.
getAttributeHint()  : string
Returns the text hint for the specified attribute.
getAttributeLabel()  : string
Returns the text label for the specified attribute.
getAttributes()  : array<string|int, mixed>
Returns attribute values.
getBehavior()  : Behavior|null
Returns the named behavior object.
getBehaviors()  : array<string|int, Behavior>
Returns all behaviors attached to this component.
getContentcontainer()  : ActiveQuery
getCreatedBy()  : User|null
Relation to User defined in created_by attribute
getDb()  : Connection
Returns the database connection used by this AR class.
getDirtyAttributes()  : array<string|int, mixed>
Returns the attribute values that have been modified since they are loaded or saved most recently.
getErrorMessage()  : string
Returns the errors as string for all attribute or a single attribute.
getErrors()  : array<string|int, mixed>
Returns the errors for all attributes or a single attribute.
getErrorSummary()  : array<string|int, mixed>
Returns the errors for all attributes as a one-dimensional array.
getFileManager()  : FileManager
Returns the file manager for this record
getFirstError()  : string|null
Returns the first error of the specified attribute.
getFirstErrors()  : array<string|int, mixed>
Returns the first error of every attribute in the model.
getIsNewRecord()  : bool
Returns a value indicating whether the current record is new.
getIterator()  : ArrayIterator
Returns an iterator for traversing the attributes in the model.
getObjectModel()  : string
Returns the class used in the polymorphic content relation.
getOldAttribute()  : mixed
Returns the old value of the named attribute.
getOldAttributes()  : array<string|int, mixed>
Returns the old attribute values.
getOldPrimaryKey()  : mixed
Returns the old primary key value(s).
getPrimaryKey()  : mixed
Returns the primary key value(s).
getRelatedRecords()  : array<string|int, mixed>
Returns all populated related records.
getRelation()  : ActiveQueryInterface|ActiveQuery|null
Returns the relation object with the specified name.
getScenario()  : string
Returns the scenario that this model is used in.
getTableSchema()  : TableSchema
Returns the schema information of the DB table associated with this AR class.
getUniqueId()  : string
Returns a unique id for this record/model
getUpdatedBy()  : User|null
Relation to User defined in updated_by attribute
getValidators()  : ArrayObject|array<string|int, Validator>
Returns all the validators declared in [[rules()]].
hasAttribute()  : bool
Returns a value indicating whether the model has an attribute with the specified name.
hasErrors()  : bool
Returns a value indicating whether there is any validation error.
hasEventHandlers()  : bool
Returns a value indicating whether there is any handler attached to the named event.
hasMany()  : ActiveQueryInterface
Declares a `has-many` relation.
hasMany()  : ActiveQuery
Declares a `has-many` relation.
hasMethod()  : bool
Returns a value indicating whether a method is defined.
hasOne()  : ActiveQueryInterface
Declares a `has-one` relation.
hasOne()  : ActiveQuery
Declares a `has-one` relation.
hasProperty()  : bool
Returns a value indicating whether a property is defined for this component.
init()  : mixed
Initializes the object.
insert()  : bool
Inserts a row into the associated database table using the attribute values of this record.
instance()  : static
Returns static class instance, which can be used to obtain meta information.
instantiate()  : static
Creates an active record instance.
isAttributeActive()  : bool
Returns a value indicating whether the attribute is active in the current scenario.
isAttributeChanged()  : bool
Returns a value indicating whether the named attribute has been changed.
isAttributeRequired()  : bool
Returns a value indicating whether the attribute is required.
isAttributeSafe()  : bool
Returns a value indicating whether the attribute is safe for massive assignments.
isPrimaryKey()  : bool
Returns a value indicating whether the given set of attributes represents the primary key for this model.
isRelationPopulated()  : bool
Check whether the named relation has been populated with records.
isTransactional()  : bool
Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].
link()  : mixed
Establishes the relationship between two models.
load()  : bool
Populates the model with input data.
loadDefaultValues()  : $this
Loads default values from database table schema.
loadMultiple()  : bool
Populates a set of models with the data from end user.
loadRelations()  : mixed
Eager loads related models for the already loaded primary model.
loadRelationsFor()  : mixed
Eager loads related models for the already loaded primary models.
markAttributeDirty()  : mixed
Marks an attribute dirty.
off()  : bool
Detaches an existing event handler from this component.
offsetExists()  : bool
Returns whether there is an element at the specified offset.
offsetGet()  : mixed
Returns the element at the specified offset.
offsetSet()  : mixed
Sets the element at the specified offset.
offsetUnset()  : mixed
Sets the element value at the specified offset to null.
on()  : mixed
Attaches an event handler to an event.
onUnsafeAttribute()  : mixed
This method is invoked when an unsafe attribute is being massively assigned.
optimisticLock()  : string|null
Returns the name of the column that stores the lock version for implementing optimistic locking.
populateRecord()  : mixed
Populates an active record object using a row of data from the database/storage.
populateRelation()  : mixed
Populates the named relation with the related records.
primaryKey()  : array<string|int, string>
Returns the primary key name(s) for this AR class.
refresh()  : bool
Repopulates this active record with the latest data.
rules()  : array<string|int, mixed>
Returns the validation rules for attributes.
safeAttributes()  : array<string|int, string>
Returns the attribute names that are safe to be massively assigned in the current scenario.
save()  : bool
Saves the current record.
scenarios()  : array<string|int, mixed>
Returns a list of scenarios and the corresponding active attributes.
setAttribute()  : mixed
Sets the named attribute value.
setAttributes()  : mixed
Sets the attribute values in a massive way.
setIsNewRecord()  : mixed
Sets the value indicating whether the record is new.
setOldAttribute()  : mixed
Sets the old value of the named attribute.
setOldAttributes()  : mixed
Sets the old attribute values.
setScenario()  : mixed
Sets the scenario for the model.
tableName()  : string
Declares the name of the database table associated with this AR class.
toArray()  : array<string|int, mixed>
Converts the model into an array.
transactions()  : array<string|int, mixed>
Declares which DB operations should be performed within a transaction in different scenarios.
trigger()  : mixed
Triggers an event.
unlink()  : mixed
Destroys the relationship between two models.
unlinkAll()  : mixed
Destroys the relationship in current model.
update()  : int|false
Saves the changes to this active record into the associated database table.
updateAll()  : int
Updates the whole table using the provided attribute values and conditions.
updateAllCounters()  : int
Updates the whole table using the provided counter changes and conditions.
updateAttributes()  : int
Updates the specified attributes.
updateCounters()  : bool
Updates one or several counter columns for the current AR object.
validate()  : bool
Performs the data validation.
validateMultiple()  : bool
Validates multiple models.
createRelationQuery()  : ActiveQueryInterface
Creates a query instance for `has-one` or `has-many` relation.
deleteInternal()  : int|false
Deletes an ActiveRecord without considering transaction.
extractFieldsFor()  : array<string|int, mixed>
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".
extractRootFields()  : array<string|int, mixed>
Extracts the root field names from nested fields.
insertInternal()  : bool
Inserts an ActiveRecord into DB without considering transaction.
refreshInternal()  : bool
Repopulates this active record with the latest data from a newly fetched instance.
resolveFields()  : array<string|int, mixed>
Determines which fields can be returned by [[toArray()]].
updateInternal()  : int|false
attachBehaviorInternal()  : Behavior
Attaches a behavior to this component.
bindModels()  : mixed
columnValueCanBeNormalized()  : bool
Check when the column value can be normalized to correct format, e.g. string formatted value '123' should be converted to integer value 123
isValueDifferent()  : bool
resetDependentRelations()  : mixed
Resets dependent related models checking if their links contain specific attribute.
setRelationDependencies()  : mixed
Sets relation dependencies for a property

Constants

EVENT_AFTER_DELETE

public mixed EVENT_AFTER_DELETE = 'afterDelete'
Tags
event

Event an event that is triggered after a record is deleted.

EVENT_AFTER_FIND

public mixed EVENT_AFTER_FIND = 'afterFind'
Tags
event

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

EVENT_AFTER_INSERT

public mixed EVENT_AFTER_INSERT = 'afterInsert'
Tags
event

AfterSaveEvent an event that is triggered after a record is inserted.

EVENT_AFTER_REFRESH

public mixed EVENT_AFTER_REFRESH = 'afterRefresh'
Tags
event

Event an event that is triggered after a record is refreshed.

since
2.0.8

EVENT_AFTER_UPDATE

public mixed EVENT_AFTER_UPDATE = 'afterUpdate'
Tags
event

AfterSaveEvent an event that is triggered after a record is updated.

EVENT_AFTER_VALIDATE

public mixed EVENT_AFTER_VALIDATE = 'afterValidate'
Tags
event

Event an event raised at the end of [[validate()]]

EVENT_APPEND_RULES

public mixed EVENT_APPEND_RULES = 'appendRules'
Tags
event

Event is used to append rules what defined in [[rules()]].

EVENT_BEFORE_DELETE

public mixed EVENT_BEFORE_DELETE = 'beforeDelete'
Tags
event

ModelEvent an event that is triggered before deleting a record. You may set [[ModelEvent::isValid]] to be false to stop the deletion.

EVENT_BEFORE_INSERT

public mixed EVENT_BEFORE_INSERT = 'beforeInsert'
Tags
event

ModelEvent an event that is triggered before inserting a record. You may set [[ModelEvent::isValid]] to be false to stop the insertion.

EVENT_BEFORE_UPDATE

public mixed EVENT_BEFORE_UPDATE = 'beforeUpdate'
Tags
event

ModelEvent an event that is triggered before updating a record. You may set [[ModelEvent::isValid]] to be false to stop the update.

EVENT_BEFORE_VALIDATE

public mixed EVENT_BEFORE_VALIDATE = 'beforeValidate'
Tags
event

ModelEvent an event raised at the beginning of [[validate()]]. You may set [[ModelEvent::isValid]] to be false to stop the validation.

EVENT_INIT

public mixed EVENT_INIT = 'init'
Tags
event

Event an event that is triggered when the record is initialized via [[init()]].

OP_ALL

All three operations: insert, update, delete.

public mixed OP_ALL = 0x7

This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE.

OP_DELETE

The delete operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.

public mixed OP_DELETE = 0x4

OP_INSERT

The insert operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.

public mixed OP_INSERT = 0x1

OP_UPDATE

The update operation. This is mainly used when overriding [[transactions()]] to specify which operations are transactional.

public mixed OP_UPDATE = 0x2

SCENARIO_DEFAULT

The name of the default scenario.

public mixed SCENARIO_DEFAULT = 'default'

Properties

$activeValidators read-only

public array<string|int, Validator> $activeValidators

The validators applicable to the current [[scenario]].

$attributes

public array<string|int, mixed> $attributes

Attribute values (name => value).

$behaviors read-only

public array<string|int, Behavior> $behaviors

List of behaviors attached to this component.

$contentcontainer

public Contentcontainer $contentcontainer

$contentcontainer_id

public int $contentcontainer_id

$created_at

public int $created_at

$dirtyAttributes read-only

public array<string|int, mixed> $dirtyAttributes

The changed attribute values (name-value pairs).

$errors read-only

public array<string|int, mixed> $errors

Errors for all attributes or the specified attribute. Empty array is returned if no error. See [[getErrors()]] for detailed description. Note that when returning errors for all attributes, the result is a two-dimensional array, like the following: php [ 'username' => [ 'Username is required.', 'Username must contain only word characters.', ], 'email' => [ 'Email address is invalid.', ] ] .

$fileManagerEnableHistory

public bool $fileManagerEnableHistory = false

enable file history for attached files

Tags
since
1.10

$firstErrors read-only

public array<string|int, mixed> $firstErrors

The first errors. The array keys are the attribute names, and the array values are the corresponding error messages. An empty array will be returned if there is no error.

$isNewRecord

public bool $isNewRecord

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

$oldAttributes

public array<string|int, mixed> $oldAttributes

The old attribute values (name-value pairs). Note that the type of this property differs in getter and setter. See [[getOldAttributes()]] and [[setOldAttributes()]] for details.

$oldPrimaryKey read-only

public mixed $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).

$primaryKey read-only

public mixed $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).

$relatedRecords read-only

public array<string|int, mixed> $relatedRecords

An array of related records indexed by relation names.

$scenario

public string $scenario

The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].

$serialized_data

public string $serialized_data

$validators read-only

public ArrayObject|array<string|int, Validator> $validators

All the validators declared in the model.

$visibility

public int $visibility

$_attributes

private array<string|int, mixed> $_attributes = []

attribute values indexed by attribute names

$_behaviors

private array<string|int, Behavior>|null $_behaviors

the attached behaviors (behavior name => behavior). This is null when not initialized.

$_errors

private array<string|int, mixed> $_errors

validation errors (attribute name => array of errors)

$_events

private array<string|int, mixed> $_events = []

the attached event handlers (event name => handlers)

$_eventWildcards

private array<string|int, mixed> $_eventWildcards = []

the event handlers attached for wildcard patterns (event name wildcard => handlers)

Tags
since
2.0.14

$_instances

private static array<string|int, static> $_instances = []

static instances in format: [className => object]

$_oldAttributes

private array<string|int, mixed>|null $_oldAttributes

old attribute values indexed by attribute names. This is null if the record [[isNewRecord|is new]].

private array<string|int, mixed> $_related = []

related models indexed by the relation names

$_relationsDependencies

private array<string|int, mixed> $_relationsDependencies = []

relation names indexed by their link attributes

$_scenario

private string $_scenario = self::SCENARIO_DEFAULT

current scenario

$_validators

private ArrayObject $_validators

list of validators

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__clone()

This method is called after the object is created by cloning an existing one.

public __clone() : mixed

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call [[init()]].

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
Parameters
$config : array<string|int, mixed> = []

name-value pairs that will be used to initialize the object properties

__get()

PHP getter magic method.

public __get(string $name) : mixed

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

Parameters
$name : string

property name

Tags
throws
InvalidArgumentException

if relation name is wrong

see
getAttribute()
Return values
mixed

property value

__isset()

Checks if a property value is null.

public __isset(string $name) : bool

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

Parameters
$name : string

the property name or the event name

Return values
bool

whether the property value is null

__serialize()

Serializes attributes and oldAttributes of this record.

public __serialize() : array<string|int, mixed>

Note: Subclasses have to include $this->getAttributes() and $this->getOldAttributes() in the serialized array.

Tags
link
http://php.net/manual/en/function.serialize.php
since
1.2
Return values
array<string|int, mixed>

__set()

PHP setter magic method.

public __set(string $name, mixed $value) : mixed

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

Parameters
$name : string

property name

$value : mixed

property value

__unserialize()

Unserializes the given string, calls the init() function and sets the attributes and oldAttributes.

public __unserialize(array<string|int, mixed> $unserializedArr) : mixed

Note: Subclasses have to call $this->init() if overwriting this function.

Parameters
$unserializedArr : array<string|int, mixed>
Tags
link
http://php.net/manual/en/function.unserialize.php

__unset()

Sets a component property to be null.

public __unset(string $name) : mixed

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

Parameters
$name : string

the property name or the event name

activeAttributes()

Returns the attribute names that are subject to validation in the current scenario.

public activeAttributes() : array<string|int, string>
Return values
array<string|int, string>

safe attribute names

addError()

Adds a new error to the specified attribute.

public addError(string $attribute[, string $error = '' ]) : mixed
Parameters
$attribute : string

attribute name

$error : string = ''

new error message

addErrors()

Adds a list of errors.

public addErrors(array<string|int, mixed> $items) : mixed
Parameters
$items : array<string|int, mixed>

a list of errors. The array keys must be attribute names. The array values should be error messages. If an attribute has multiple errors, these errors must be given in terms of an array. You may use the result of [[getErrors()]] as the value for this parameter.

Tags
since
2.0.2

afterDelete()

This method is invoked after deleting a record.

public afterDelete() : mixed

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.

afterFind()

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

public afterFind() : mixed

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.

afterRefresh()

This method is called when the AR object is refreshed.

public afterRefresh() : mixed

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.

Tags
since
2.0.8

afterSave()

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

public afterSave(mixed $insert, mixed $changedAttributes) : mixed
Parameters
$insert : mixed

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

$changedAttributes : mixed

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 https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.

Tags
inheritdoc

afterValidate()

This method is invoked after validation ends.

public afterValidate() : mixed

The default implementation raises an afterValidate event. You may override this method to do postprocessing after validation. Make sure the parent implementation is invoked so that the event can be raised.

attachBehavior()

Attaches a behavior to this component.

public attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.

Parameters
$name : string

the name of the behavior.

$behavior : string|array<string|int, mixed>|Behavior

the behavior configuration. This can be one of the following:

  • a [[Behavior]] object
  • a string specifying the behavior class
  • an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
see
detachBehavior()
Return values
Behavior

the behavior object

attachBehaviors()

Attaches a list of behaviors to the component.

public attachBehaviors(array<string|int, mixed> $behaviors) : mixed

Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.

Parameters
$behaviors : array<string|int, mixed>

list of behaviors to be attached to the component

Tags
see
attachBehavior()

attributeHints()

Returns the attribute hints.

public attributeHints() : array<string|int, mixed>

Attribute hints are mainly used for display purpose. For example, given an attribute isPublic, we can declare a hint Whether the post should be visible for not logged in users, which provides user-friendly description of the attribute meaning and can be displayed to end users.

Unlike label hint will not be generated, if its explicit declaration is omitted.

Note, in order to inherit hints defined in the parent class, a child class needs to merge the parent hints with child hints using functions such as array_merge().

Tags
since
2.0.4
Return values
array<string|int, mixed>

attribute hints (name => hint)

attributeLabels()

Returns the attribute labels.

public attributeLabels() : array<string|int, mixed>

Attribute labels are mainly used for display purpose. For example, given an attribute firstName, we can declare a label First Name which is more user-friendly and can be displayed to end users.

By default an attribute label is generated using [[generateAttributeLabel()]]. This method allows you to explicitly specify attribute labels.

Note, in order to inherit labels defined in the parent class, a child class needs to merge the parent labels with child labels using functions such as array_merge().

Tags
see
generateAttributeLabel()
Return values
array<string|int, mixed>

attribute labels (name => label)

attributes()

Returns the list of all attribute names of the model.

public attributes() : array<string|int, mixed>

The default implementation will return all column names of the table associated with this AR class.

Return values
array<string|int, mixed>

list of attribute names.

beforeDelete()

This method is invoked before deleting a record.

public beforeDelete() : bool

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;
}
Return values
bool

whether the record should be deleted. Defaults to true.

beforeSave()

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

public beforeSave(mixed $insert) : bool
Parameters
$insert : mixed

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

Tags
inheritdoc
Return values
bool

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

beforeValidate()

This method is invoked before validation starts.

public beforeValidate() : bool

The default implementation raises a beforeValidate event. You may override this method to do preliminary checks before validation. Make sure the parent implementation is invoked so that the event can be raised.

Return values
bool

whether the validation should be executed. Defaults to true. If false is returned, the validation will stop and the model is considered invalid.

behaviors()

Returns a list of behaviors that this component should behave as.

public behaviors() : array<string|int, mixed>

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

Return values
array<string|int, mixed>

the behavior configurations.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(mixed $name[, mixed $checkVars = true ][, mixed $checkBehaviors = true ]) : bool
Parameters
$name : mixed

the property name

$checkVars : mixed = true

whether to treat member variables as properties

$checkBehaviors : mixed = true

whether to treat behaviors' properties as properties of this component

Return values
bool

whether the property can be read

canSetOldAttribute()

Returns if the old named attribute can be set.

public canSetOldAttribute(string $name) : bool
Parameters
$name : string

the attribute name

Tags
see
setOldAttribute()
Return values
bool

whether the old attribute can be set

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(mixed $name[, mixed $checkVars = true ][, mixed $checkBehaviors = true ]) : bool
Parameters
$name : mixed

the property name

$checkVars : mixed = true

whether to treat member variables as properties

$checkBehaviors : mixed = true

whether to treat behaviors' properties as properties of this component

Return values
bool

whether the property can be written

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

clearErrors()

Removes errors for all attributes or a single attribute.

public clearErrors([string|null $attribute = null ]) : mixed
Parameters
$attribute : string|null = null

attribute name. Use null to remove errors for all attributes.

createValidators()

Creates validator objects based on the validation rules specified in [[rules()]].

public createValidators() : ArrayObject
Tags
inheritdoc
Return values
ArrayObject

validators

delete()

Deletes the table row corresponding to this active record.

public delete() : int|false

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.

Tags
throws
StaleObjectException

if [[optimisticLock|optimistic locking]] is enabled and the data being deleted is outdated.

throws
Throwable

in case delete failed.

Return values
int|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.

deleteAll()

Deletes rows in the table using the provided conditions.

public static deleteAll([string|array<string|int, mixed>|null $condition = null ][, array<string|int, mixed> $params = [] ]) : int

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

Customer::deleteAll('status = 3');

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

Note that this method will not trigger any events. If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first and then call [[delete()]] on each of them. For example an equivalent of the example above would be:

$models = Customer::find()->where('status = 3')->all();
foreach ($models as $model) {
    $model->delete();
}

For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.

Parameters
$condition : string|array<string|int, mixed>|null = null

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

$params : array<string|int, mixed> = []

the parameters (name => value) to be bound to the query.

Return values
int

the number of rows deleted

detachBehavior()

Detaches a behavior from the component.

public detachBehavior(string $name) : Behavior|null

The behavior's [[Behavior::detach()]] method will be invoked.

Parameters
$name : string

the behavior's name.

Return values
Behavior|null

the detached behavior. Null if the behavior does not exist.

detachBehaviors()

Detaches all behaviors from the component.

public detachBehaviors() : mixed

ensureBehaviors()

Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.

public ensureBehaviors() : mixed

equals()

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

public equals(ActiveRecord $record) : bool

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

Parameters
$record : ActiveRecord

record to compare to

Return values
bool

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

extraFields()

Returns the list of additional fields that can be returned by [[toArray()]] in addition to those listed in [[fields()]].

public extraFields() : array<string|int, mixed>

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

Return values
array<string|int, mixed>

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.

public fields() : array<string|int, mixed>

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

Return values
array<string|int, mixed>

the list of field names or field definitions.

find()

Creates an [[ActiveQueryInterface]] instance for query purpose.

public static find() : ActiveQuery
Return values
ActiveQuery

the newly created [[ActiveQuery]] instance.

findAll()

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

public static findAll(mixed $condition) : array<string|int, static>
Parameters
$condition : mixed

primary key value or a set of column values

Return values
array<string|int, static>

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

findBySql()

Creates an [[ActiveQuery]] instance with a given SQL statement.

public static findBySql(string $sql[, array<string|int, mixed> $params = [] ]) : ActiveQuery

Note that because the SQL statement is already specified, calling additional query modification methods (such as where(), order()) on the created [[ActiveQuery]] instance will have no effect. However, calling with(), asArray() or indexBy() is still fine.

Below is an example:

$customers = Customer::findBySql('SELECT * FROM customer')->all();
Parameters
$sql : string

the SQL statement to be executed

$params : array<string|int, mixed> = []

parameters to be bound to the SQL statement during execution.

Return values
ActiveQuery

the newly created [[ActiveQuery]] instance

findOne()

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

public static findOne(mixed $condition) : static|null
Parameters
$condition : mixed

primary key value or a set of column values

Return values
static|null

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

formName()

Returns the form name that this model class should use.

public formName() : string

The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name the input fields for the attributes in a model. If the form name is "A" and an attribute name is "b", then the corresponding input name would be "A[b]". If the form name is an empty string, then the input name would be "b".

The purpose of the above naming schema is that for forms which contain multiple different models, the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to differentiate between them.

By default, this method returns the model class name (without the namespace part) as the form name. You may override it when the model is used in different forms.

Tags
see
load()
throws
InvalidConfigException

when form is defined with anonymous class and formName() method is not overridden.

Return values
string

the form name of this model class.

generateAttributeLabel()

Generates a user friendly attribute label based on the give attribute name.

public generateAttributeLabel(string $name) : string

This is done by replacing underscores, dashes and dots with blanks and changing the first letter of each word to upper case. For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.

Parameters
$name : string

the column name

Return values
string

the attribute label

getActiveValidators()

Returns the validators applicable to the current [[scenario]].

public getActiveValidators([string|null $attribute = null ]) : array<string|int, Validator>
Parameters
$attribute : string|null = null

the name of the attribute whose applicable validators should be returned. If this is null, the validators for ALL attributes in the model will be returned.

Return values
array<string|int, Validator>

the validators applicable to the current [[scenario]].

getAttribute()

Returns the named attribute value.

public getAttribute(string $name) : mixed

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

Parameters
$name : string

the attribute name

Tags
see
hasAttribute()
Return values
mixed

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

getAttributeHint()

Returns the text hint for the specified attribute.

public getAttributeHint(string $attribute) : string

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

Parameters
$attribute : string

the attribute name

Tags
see
attributeHints()
since
2.0.4
Return values
string

the attribute hint

getAttributeLabel()

Returns the text label for the specified attribute.

public getAttributeLabel(mixed $attribute) : string
Parameters
$attribute : mixed

the attribute name

Tags
inheritdoc
Return values
string

the attribute label

getAttributes()

Returns attribute values.

public getAttributes([array<string|int, mixed>|null $names = null ][, array<string|int, mixed> $except = [] ]) : array<string|int, mixed>
Parameters
$names : array<string|int, mixed>|null = null

list of attributes whose value needs to be returned. Defaults to null, meaning all attributes listed in [[attributes()]] will be returned. If it is an array, only the attributes in the array will be returned.

$except : array<string|int, mixed> = []

list of attributes whose value should NOT be returned.

Return values
array<string|int, mixed>

attribute values (name => value).

getBehavior()

Returns the named behavior object.

public getBehavior(string $name) : Behavior|null
Parameters
$name : string

the behavior name

Return values
Behavior|null

the behavior object, or null if the behavior does not exist

getBehaviors()

Returns all behaviors attached to this component.

public getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior>

list of behaviors attached to this component

getCreatedBy()

Relation to User defined in created_by attribute

public getCreatedBy() : User|null
Return values
User|null

getDb()

Returns the database connection used by this AR class.

public static getDb() : Connection

By default, the "db" application component is used as the database connection. You may override this method if you want to use a different database connection.

Return values
Connection

the database connection used by this AR class.

getDirtyAttributes()

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

public getDirtyAttributes([array<string|int, string>|null $names = null ]) : array<string|int, mixed>

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

Parameters
$names : array<string|int, string>|null = null

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

Return values
array<string|int, mixed>

the changed attribute values (name-value pairs)

getErrorMessage()

Returns the errors as string for all attribute or a single attribute.

public getErrorMessage([string $attribute = null ]) : string
Parameters
$attribute : string = null

attribute name. Use null to retrieve errors for all attributes.

Tags
since
1.2
Return values
string

the error message

getErrors()

Returns the errors for all attributes or a single attribute.

public getErrors([string|null $attribute = null ]) : array<string|int, mixed>
Parameters
$attribute : string|null = null

attribute name. Use null to retrieve errors for all attributes.

Tags
see
getFirstErrors()
see
getFirstError()
Return values
array<string|int, mixed>

errors for all attributes or the specified attribute. Empty array is returned if no error. See [[getErrors()]] for detailed description. Note that when returning errors for all attributes, the result is a two-dimensional array, like the following:

[
    'username' => [
        'Username is required.',
        'Username must contain only word characters.',
    ],
    'email' => [
        'Email address is invalid.',
    ]
]

getErrorSummary()

Returns the errors for all attributes as a one-dimensional array.

public getErrorSummary(bool $showAllErrors) : array<string|int, mixed>
Parameters
$showAllErrors : bool

boolean, if set to true every error message for each attribute will be shown otherwise only the first error message for each attribute will be shown.

Tags
see
getErrors()
see
getFirstErrors()
since
2.0.14
Return values
array<string|int, mixed>

errors for all attributes as a one-dimensional array. Empty array is returned if no error.

getFirstError()

Returns the first error of the specified attribute.

public getFirstError(string $attribute) : string|null
Parameters
$attribute : string

attribute name.

Tags
see
getErrors()
see
getFirstErrors()
Return values
string|null

the error message. Null is returned if no error.

getFirstErrors()

Returns the first error of every attribute in the model.

public getFirstErrors() : array<string|int, mixed>
Tags
see
getErrors()
see
getFirstError()
Return values
array<string|int, mixed>

the first errors. The array keys are the attribute names, and the array values are the corresponding error messages. An empty array will be returned if there is no error.

getIsNewRecord()

Returns a value indicating whether the current record is new.

public getIsNewRecord() : bool
Return values
bool

whether the record is new and should be inserted when calling [[save()]].

getIterator()

Returns an iterator for traversing the attributes in the model.

public getIterator() : ArrayIterator

This method is required by the interface [[\IteratorAggregate]].

Attributes
#[ReturnTypeWillChange]
Return values
ArrayIterator

an iterator for traversing the items in the list.

getObjectModel()

Returns the class used in the polymorphic content relation.

public static getObjectModel() : string

By default, this function will return the static class.

Subclasses of existing content record classes may overwrite this function in order to remain the actual base type as follows:

public static function getObjectModel(): string {
    return BaseType::class
}

This will force the usage of the BaseType class when creating, deleting or querying the content relation. This is used in cases in which a subclass extends the a base record class without implementing a custom content type.

Return values
string

getOldAttribute()

Returns the old value of the named attribute.

public getOldAttribute(string $name) : mixed

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

Parameters
$name : string

the attribute name

Tags
see
hasAttribute()
Return values
mixed

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

getOldAttributes()

Returns the old attribute values.

public getOldAttributes() : array<string|int, mixed>
Return values
array<string|int, mixed>

the old attribute values (name-value pairs)

getOldPrimaryKey()

Returns the old primary key value(s).

public getOldPrimaryKey([bool $asArray = false ]) : mixed

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.

Parameters
$asArray : bool = false

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.

Tags
throws
Exception

if the AR model does not have a primary key

Return values
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).

getPrimaryKey()

Returns the primary key value(s).

public getPrimaryKey([bool $asArray = false ]) : mixed
Parameters
$asArray : bool = false

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 values
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.

public getRelatedRecords() : array<string|int, mixed>
Tags
see
getRelation()
Return values
array<string|int, mixed>

an array of related records indexed by relation names.

getRelation()

Returns the relation object with the specified name.

public getRelation(string $name[, bool $throwException = true ]) : ActiveQueryInterface|ActiveQuery|null

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

Parameters
$name : string

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

$throwException : bool = true

whether to throw exception if the relation does not exist.

Tags
throws
InvalidArgumentException

if the named relation does not exist.

Return values
ActiveQueryInterface|ActiveQuery|null

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

getScenario()

Returns the scenario that this model is used in.

public getScenario() : string

Scenario affects how validation is performed and which attributes can be massively assigned.

Return values
string

the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].

getTableSchema()

Returns the schema information of the DB table associated with this AR class.

public static getTableSchema() : TableSchema
Tags
throws
InvalidConfigException

if the table for the AR class does not exist.

Return values
TableSchema

the schema information of the DB table associated with this AR class.

getUniqueId()

Returns a unique id for this record/model

public getUniqueId() : string
Return values
string

Unique Id of this record

getUpdatedBy()

Relation to User defined in updated_by attribute

public getUpdatedBy() : User|null
Return values
User|null

getValidators()

Returns all the validators declared in [[rules()]].

public getValidators() : ArrayObject|array<string|int, Validator>

This method differs from [[getActiveValidators()]] in that the latter only returns the validators applicable to the current [[scenario]].

Because this method returns an ArrayObject object, you may manipulate it by inserting or removing validators (useful in model behaviors). For example,

$model->validators[] = $newValidator;
Return values
ArrayObject|array<string|int, Validator>

all the validators declared in the model.

hasAttribute()

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

public hasAttribute(string $name) : bool
Parameters
$name : string

the name of the attribute

Return values
bool

whether the model has an attribute with the specified name.

hasErrors()

Returns a value indicating whether there is any validation error.

public hasErrors([string|null $attribute = null ]) : bool
Parameters
$attribute : string|null = null

attribute name. Use null to check all attributes.

Return values
bool

whether there is any error.

hasEventHandlers()

Returns a value indicating whether there is any handler attached to the named event.

public hasEventHandlers(string $name) : bool
Parameters
$name : string

the event name

Return values
bool

whether there is any handler attached to the event.

hasMany()

Declares a `has-many` relation.

public hasMany(string $class, array<string|int, mixed> $link) : ActiveQueryInterface

The declaration is returned in terms of a relational [[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::class, ['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 [[ActiveQuery]] to further customize the relation.

Parameters
$class : string

the class name of the related record

$link : array<string|int, mixed>

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 values
ActiveQueryInterface

the relational query object.

hasMany()

Declares a `has-many` relation.

public hasMany([mixed $class = ][, array<string|int, mixed> $link = ]) : ActiveQuery

See [[BaseActiveRecord::hasMany()]] for more info.

Parameters
$class : mixed =

the class name of the related record

$link : array<string|int, mixed> =

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 values
ActiveQuery

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name[, bool $checkBehaviors = true ]) : bool

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkBehaviors : bool = true

whether to treat behaviors' methods as methods of this component

Return values
bool

whether the method is defined

hasOne()

Declares a `has-one` relation.

public hasOne(string $class, array<string|int, mixed> $link) : ActiveQueryInterface

The declaration is returned in terms of a relational [[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::class, ['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 [[ActiveQuery]] to further customize the relation.

Parameters
$class : string

the class name of the related record

$link : array<string|int, mixed>

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 values
ActiveQueryInterface

the relational query object.

hasOne()

Declares a `has-one` relation.

public hasOne([mixed $class = ][, array<string|int, mixed> $link = ]) : ActiveQuery

See [[BaseActiveRecord::hasOne()]] for more info.

Parameters
$class : mixed =

the class name of the related record

$link : array<string|int, mixed> =

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 values
ActiveQuery

hasProperty()

Returns a value indicating whether a property is defined for this component.

public hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property is defined if:

  • the class has a getter or 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 property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

init()

Initializes the object.

public init() : mixed

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

insert()

Inserts a row into the associated database table using the attribute values of this record.

public insert([bool $runValidation = true ][, array<string|int, mixed>|null $attributes = null ]) : bool

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. insert 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_INSERT]], and [[EVENT_AFTER_INSERT]] will be raised by the corresponding methods.

Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.

If the table's primary key is auto-incremental and is null during insertion, it will be populated with the actual value after insertion.

For example, to insert a customer record:

$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
Parameters
$runValidation : bool = true

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.

$attributes : array<string|int, mixed>|null = null

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

Tags
throws
Throwable

in case insert failed.

Return values
bool

whether the attributes are valid and the record is inserted successfully.

instance()

Returns static class instance, which can be used to obtain meta information.

public static instance([bool $refresh = false ]) : static
Parameters
$refresh : bool = false

whether to re-create static instance even, if it is already cached.

Return values
static

class instance.

instantiate()

Creates an active record instance.

public static instantiate(array<string|int, mixed> $row) : static

This method is called together with [[populateRecord()]] by [[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.

Parameters
$row : array<string|int, mixed>

row data to be populated into the record.

Return values
static

the newly created active record

isAttributeActive()

Returns a value indicating whether the attribute is active in the current scenario.

public isAttributeActive(string $attribute) : bool
Parameters
$attribute : string

attribute name

Tags
see
activeAttributes()
Return values
bool

whether the attribute is active in the current scenario

isAttributeChanged()

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

public isAttributeChanged(string $name[, bool $identical = true ]) : bool
Parameters
$name : string

the name of the attribute.

$identical : bool = true

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 values
bool

whether the attribute has been changed

isAttributeRequired()

Returns a value indicating whether the attribute is required.

public isAttributeRequired(string $attribute) : bool

This is determined by checking if the attribute is associated with a [[\yii\validators\RequiredValidator|required]] validation rule in the current [[scenario]].

Note that when the validator has a conditional validation applied using [[\yii\validators\RequiredValidator::$when|$when]] this method will return false regardless of the when condition because it may be called be before the model is loaded with data.

Parameters
$attribute : string

attribute name

Return values
bool

whether the attribute is required

isAttributeSafe()

Returns a value indicating whether the attribute is safe for massive assignments.

public isAttributeSafe(string $attribute) : bool
Parameters
$attribute : string

attribute name

Tags
see
safeAttributes()
Return values
bool

whether the attribute is safe for massive assignments

isPrimaryKey()

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

public static isPrimaryKey(array<string|int, mixed> $keys) : bool
Parameters
$keys : array<string|int, mixed>

the set of attributes to check

Return values
bool

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

isRelationPopulated()

Check whether the named relation has been populated with records.

public isRelationPopulated(string $name) : bool
Parameters
$name : string

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

Tags
see
getRelation()
Return values
bool

whether relation has been populated with records.

isTransactional()

Returns a value indicating whether the specified operation is transactional in the current [[$scenario]].

public isTransactional(int $operation) : bool
Parameters
$operation : int

the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]].

Return values
bool

whether the specified operation is transactional in the current [[scenario]].

Establishes the relationship between two models.

public link(string $name, ActiveRecordInterface $model[, array<string|int, mixed> $extraColumns = [] ]) : mixed

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 and without events/behaviors.

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.

Parameters
$name : string

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

$model : ActiveRecordInterface

the model to be linked with the current one.

$extraColumns : array<string|int, mixed> = []

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 [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)

Tags
throws
InvalidCallException

if the method is unable to link two models.

load()

Populates the model with input data.

public load(array<string|int, mixed> $data[, string|null $formName = null ]) : bool

This method provides a convenient shortcut for:

if (isset($_POST['FormName'])) {
    $model->attributes = $_POST['FormName'];
    if ($model->save()) {
        // handle success
    }
}

which, with load() can be written as:

if ($model->load($_POST) && $model->save()) {
    // handle success
}

load() gets the 'FormName' from the model's [[formName()]] method (which you may override), unless the $formName parameter is given. If the form name is empty, load() populates the model with the whole of $data, instead of $data['FormName'].

Note, that the data being populated is subject to the safety check by [[setAttributes()]].

Parameters
$data : array<string|int, mixed>

the data array to load, typically $_POST or $_GET.

$formName : string|null = null

the form name to use to load the data into the model, empty string when form not use. If not set, [[formName()]] is used.

Return values
bool

whether load() found the expected form in $data.

loadDefaultValues()

Loads default values from database table schema.

public loadDefaultValues([bool $skipIfSet = true ]) : $this

You may call this method to load default values after creating a new instance:

// class Customer extends \yii\db\ActiveRecord
$customer = new Customer();
$customer->loadDefaultValues();
Parameters
$skipIfSet : bool = true

whether existing value should be preserved. This will only set defaults for attributes that are null.

Return values
$this

the model instance itself.

loadMultiple()

Populates a set of models with the data from end user.

public static loadMultiple(array<string|int, mixed> $models, array<string|int, mixed> $data[, string|null $formName = null ]) : bool

This method is mainly used to collect tabular data input. The data to be loaded for each model is $data[formName][index], where formName refers to the value of [[formName()]], and index the index of the model in the $models array. If [[formName()]] is empty, $data[index] will be used to populate each model. The data being populated to each model is subject to the safety check by [[setAttributes()]].

Parameters
$models : array<string|int, mixed>

the models to be populated. Note that all models should have the same class.

$data : array<string|int, mixed>

the data array. This is usually $_POST or $_GET, but can also be any valid array supplied by end user.

$formName : string|null = null

the form name to be used for loading the data into the models. If not set, it will use the [[formName()]] value of the first model in $models. This parameter is available since version 2.0.1.

Return values
bool

whether at least one of the models is successfully populated.

loadRelations()

Eager loads related models for the already loaded primary model.

public loadRelations(string|array<string|int, mixed> $relationNames[, bool $asArray = false ]) : mixed

Helps to reduce the number of queries performed against database if some related models are only used when a specific condition is met. For example:

$customer = Customer::find()->where(['id' => 123])->one();
if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
    $customer->loadRelations('orders.items');
}
Parameters
$relationNames : string|array<string|int, mixed>

the names of the relations of this model to be loaded from database. See [[ActiveQueryInterface::with()]] on how to specify this argument.

$asArray : bool = false

whether to load each relation as an array or an object (if the relation itself does not specify that).

Tags
since
2.0.50

loadRelationsFor()

Eager loads related models for the already loaded primary models.

public static loadRelationsFor(array<string|int, mixed>|array<string|int, ActiveRecordInterface&$models, string|array<string|int, mixed> $relationNames[, bool $asArray = false ]) : mixed

Helps to reduce the number of queries performed against database if some related models are only used when a specific condition is met. For example:

$customers = Customer::find()->where(['country_id' => 123])->all();
if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
    Customer::loadRelationsFor($customers, 'orders.items');
}
Parameters
$models : array<string|int, mixed>|array<string|int, ActiveRecordInterface>

array of primary models. Each model should have the same type and can be:

  • an active record instance;
  • active record instance represented by array (i.e. active record was loaded using [[ActiveQuery::asArray()]]).
$relationNames : string|array<string|int, mixed>

the names of the relations of primary models to be loaded from database. See [[ActiveQueryInterface::with()]] on how to specify this argument.

$asArray : bool = false

whether to load each related model as an array or an object (if the relation itself does not specify that).

Tags
since
2.0.50

markAttributeDirty()

Marks an attribute dirty.

public markAttributeDirty(string $name) : mixed

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

Parameters
$name : string

the attribute name

off()

Detaches an existing event handler from this component.

public off(string $name[, callable|null $handler = null ]) : bool

This method is the opposite of [[on()]].

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

Parameters
$name : string

event name

$handler : callable|null = null

the event handler to be removed. If it is null, all handlers attached to the named event will be removed.

Tags
see
on()
Return values
bool

if a handler is found and detached

offsetExists()

Returns whether there is an element at the specified offset.

public offsetExists(mixed $offset) : bool

This method is required by the interface [[\ArrayAccess]].

Parameters
$offset : mixed

the offset to check on

Attributes
#[ReturnTypeWillChange]
Return values
bool

whether there is an element at the specified offset.

offsetGet()

Returns the element at the specified offset.

public offsetGet(string $offset) : mixed

This method is required by the SPL interface [[\ArrayAccess]]. It is implicitly called when you use something like $value = $model[$offset];.

Parameters
$offset : string

the offset to retrieve element.

Attributes
#[ReturnTypeWillChange]
Return values
mixed

the element at the offset, null if no element is found at the offset

offsetSet()

Sets the element at the specified offset.

public offsetSet(string $offset, mixed $value) : mixed

This method is required by the SPL interface [[\ArrayAccess]]. It is implicitly called when you use something like $model[$offset] = $value;.

Parameters
$offset : string

the offset to set element

$value : mixed

the element value

Attributes
#[ReturnTypeWillChange]

offsetUnset()

Sets the element value at the specified offset to null.

public offsetUnset(mixed $offset) : mixed

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

Parameters
$offset : mixed

the offset to unset element

on()

Attaches an event handler to an event.

public on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

The event handler must be defined with the following signature,

function ($event)

where $event is an [[Event]] object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});
Parameters
$name : string

the event name

$handler : callable

the event handler

$data : mixed = null

the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].

$append : bool = true

whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

Tags
see
off()

onUnsafeAttribute()

This method is invoked when an unsafe attribute is being massively assigned.

public onUnsafeAttribute(string $name, mixed $value) : mixed

The default implementation will log a warning message if YII_DEBUG is on. It does nothing otherwise.

Parameters
$name : string

the unsafe attribute name

$value : mixed

the attribute value

optimisticLock()

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

public optimisticLock() : string|null

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 [[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 [[\yii\behaviors\OptimisticLockBehavior|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 record being updated.
  4. In the controller action that does the data updating, try to catch the [[StaleObjectException]] and implement necessary business logic (e.g. merging the changes, prompting stated data) to resolve the conflict.
Return values
string|null

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.

public static populateRecord(mixed $record, mixed $row) : mixed
Parameters
$record : mixed

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

$row : mixed

attribute values (name => value)

populateRelation()

Populates the named relation with the related records.

public populateRelation(string $name, ActiveRecordInterface|array<string|int, mixed>|null $records) : mixed

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

Parameters
$name : string

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

$records : ActiveRecordInterface|array<string|int, mixed>|null

the related records to be populated into the relation.

Tags
see
getRelation()

primaryKey()

Returns the primary key name(s) for this AR class.

public static primaryKey() : array<string|int, string>

The default implementation will return the primary key(s) as declared in the DB table that is associated with this AR class.

If the DB table does not declare any primary key, you should override this method to return the attributes that you want to use as primary keys for this AR class.

Note that an array should be returned even for a table with single primary key.

Return values
array<string|int, string>

the primary keys of the associated database table.

refresh()

Repopulates this active record with the latest data.

public refresh() : bool
Return values
bool

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.

rules()

Returns the validation rules for attributes.

public rules() : array<string|int, mixed>
Tags
inheritdoc
Return values
array<string|int, mixed>

validation rules

safeAttributes()

Returns the attribute names that are safe to be massively assigned in the current scenario.

public safeAttributes() : array<string|int, string>
Return values
array<string|int, string>

safe attribute names

save()

Saves the current record.

public save([bool $runValidation = true ][, array<string|int, mixed>|null $attributeNames = null ]) : bool

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();
Parameters
$runValidation : bool = true

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<string|int, mixed>|null = null

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

Tags
throws
Exception

in case update or insert failed.

Return values
bool

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

scenarios()

Returns a list of scenarios and the corresponding active attributes.

public scenarios() : array<string|int, mixed>

An active attribute is one that is subject to validation in the current scenario. The returned array should be in the following format:

[
    'scenario1' => ['attribute11', 'attribute12', ...],
    'scenario2' => ['attribute21', 'attribute22', ...],
    ...
]

By default, an active attribute is considered safe and can be massively assigned. If an attribute should NOT be massively assigned (thus considered unsafe), please prefix the attribute with an exclamation character (e.g. '!rank').

The default implementation of this method will return all scenarios found in the [[rules()]] declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes found in the [[rules()]]. Each scenario will be associated with the attributes that are being validated by the validation rules that apply to the scenario.

Return values
array<string|int, mixed>

a list of scenarios and the corresponding active attributes.

setAttribute()

Sets the named attribute value.

public setAttribute(string $name, mixed $value) : mixed
Parameters
$name : string

the attribute name

$value : mixed

the attribute value.

Tags
throws
InvalidArgumentException

if the named attribute does not exist.

see
hasAttribute()

setAttributes()

Sets the attribute values in a massive way.

public setAttributes(mixed $values[, mixed $safeOnly = true ]) : mixed
Parameters
$values : mixed

attribute values (name => value) to be assigned to the model.

$safeOnly : mixed = true

whether the assignments should only be done to the safe attributes. A safe attribute is one that is associated with a validation rule in the current [[scenario]].

Tags
inheritdoc

setIsNewRecord()

Sets the value indicating whether the record is new.

public setIsNewRecord(bool $value) : mixed
Parameters
$value : bool

whether the record is new and should be inserted when calling [[save()]].

Tags
see
getIsNewRecord()

setOldAttribute()

Sets the old value of the named attribute.

public setOldAttribute(string $name, mixed $value) : mixed
Parameters
$name : string

the attribute name

$value : mixed

the old attribute value.

Tags
throws
InvalidArgumentException

if the named attribute does not exist.

see
hasAttribute()

setOldAttributes()

Sets the old attribute values.

public setOldAttributes(array<string|int, mixed>|null $values) : mixed

All existing old attribute values will be discarded.

Parameters
$values : array<string|int, mixed>|null

old attribute values to be set. If set to null this record is considered to be [[isNewRecord|new]].

setScenario()

Sets the scenario for the model.

public setScenario(string $value) : mixed

Note that this method does not check if the scenario exists or not. The method [[validate()]] will perform this check.

Parameters
$value : string

the scenario that this model is in.

tableName()

Declares the name of the database table associated with this AR class.

public static tableName() : string
Tags
inheritdoc
Return values
string

the table name

toArray()

Converts the model into an array.

public toArray([array<string|int, mixed> $fields = [] ][, array<string|int, mixed> $expand = [] ][, bool $recursive = true ]) : array<string|int, mixed>

This method will first identify which fields to be included in the resulting array by calling [[resolveFields()]]. It will then turn the model into an array with these fields. If $recursive is true, any embedded objects will also be converted into arrays. When embedded objects are [[Arrayable]], their respective nested fields will be extracted and passed to [[toArray()]].

If the model implements the [[Linkable]] interface, the resulting array will also have a _link element which refers to a list of links as specified by the interface.

Parameters
$fields : array<string|int, mixed> = []

the fields being requested. If empty or if it contains '*', all fields as specified by [[fields()]] will be returned. Fields can be nested, separated with dots (.). e.g.: item.field.sub-field $recursive must be true for nested fields to be extracted. If $recursive is false, only the root fields will be extracted.

$expand : array<string|int, mixed> = []

the additional fields being requested for exporting. Only fields declared in [[extraFields()]] will be considered. Expand can also be nested, separated with dots (.). e.g.: item.expand1.expand2 $recursive must be true for nested expands to be extracted. If $recursive is false, only the root expands will be extracted.

$recursive : bool = true

whether to recursively return array representation of embedded objects.

Return values
array<string|int, mixed>

the array representation of the object

transactions()

Declares which DB operations should be performed within a transaction in different scenarios.

public transactions() : array<string|int, mixed>

The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]], which correspond to the [[insert()]], [[update()]] and [[delete()]] methods, respectively. By default, these methods are NOT enclosed in a DB transaction.

In some scenarios, to ensure data consistency, you may want to enclose some or all of them in transactions. You can do so by overriding this method and returning the operations that need to be transactional. For example,

return [
    'admin' => self::OP_INSERT,
    'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
    // the above is equivalent to the following:
    // 'api' => self::OP_ALL,

];

The above declaration specifies that in the "admin" scenario, the insert operation ([[insert()]]) should be done in a transaction; and in the "api" scenario, all the operations should be done in a transaction.

Return values
array<string|int, mixed>

the declarations of transactional operations. The array keys are scenarios names, and the array values are the corresponding transaction operations.

trigger()

Triggers an event.

public trigger(string $name[, Event|null $event = null ]) : mixed

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

Parameters
$name : string

the event name

$event : Event|null = null

the event instance. If not set, a default [[Event]] object will be created.

Destroys the relationship between two models.

public unlink(string $name, ActiveRecordInterface $model[, bool $delete = false ]) : mixed

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.

Parameters
$name : string

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

$model : 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 : bool = false

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.

Tags
throws
InvalidCallException

if the models cannot be unlinked

throws
Exception
throws
StaleObjectException

unlinkAll()

Destroys the relationship in current model.

public unlinkAll(string $name[, bool $delete = false ]) : mixed

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

Parameters
$name : string

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

$delete : bool = false

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()|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.

public update([bool $runValidation = true ][, array<string|int, mixed>|null $attributeNames = null ]) : int|false

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 [[dirtyAttributes|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
}
Parameters
$runValidation : bool = true

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<string|int, mixed>|null = null

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

Tags
throws
StaleObjectException

if [[optimisticLock|optimistic locking]] is enabled and the data being updated is outdated.

throws
Throwable

in case update failed.

Return values
int|false

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

updateAll()

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

public static updateAll(array<string|int, mixed> $attributes[, string|array<string|int, mixed> $condition = '' ][, array<string|int, mixed> $params = [] ]) : int

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

Customer::updateAll(['status' => 1], 'status = 2');

Warning: If you do not specify any condition, this method will update all rows in the table.

Note that this method will not trigger any events. If you need [[EVENT_BEFORE_UPDATE]] or [[EVENT_AFTER_UPDATE]] to be triggered, you need to [[find()|find]] the models first and then call [[update()]] on each of them. For example an equivalent of the example above would be:

$models = Customer::find()->where('status = 2')->all();
foreach ($models as $model) {
    $model->status = 1;
    $model->update(false); // skipping validation as no user input is involved
}

For a large set of models you might consider using [[ActiveQuery::each()]] to keep memory usage within limits.

Parameters
$attributes : array<string|int, mixed>

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

$condition : string|array<string|int, mixed> = ''

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

$params : array<string|int, mixed> = []

the parameters (name => value) to be bound to the query.

Return values
int

the number of rows updated

updateAllCounters()

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

public static updateAllCounters(array<string|int, mixed> $counters[, string|array<string|int, mixed> $condition = '' ][, array<string|int, mixed> $params = [] ]) : int

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

Customer::updateAllCounters(['age' => 1]);

Note that this method will not trigger any events.

Parameters
$counters : array<string|int, mixed>

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

$condition : string|array<string|int, mixed> = ''

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

$params : array<string|int, mixed> = []

the parameters (name => value) to be bound to the query. Do not name the parameters as :bp0, :bp1, etc., because they are used internally by this method.

Return values
int

the number of rows updated

updateAttributes()

Updates the specified attributes.

public updateAttributes(array<string|int, mixed> $attributes) : int

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.

Parameters
$attributes : array<string|int, mixed>

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

Return values
int

the number of rows affected.

updateCounters()

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

public updateCounters(array<string|int, mixed> $counters) : bool

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]);
Parameters
$counters : array<string|int, mixed>

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

Tags
see
updateAllCounters()
Return values
bool

whether the saving is successful

validate()

Performs the data validation.

public validate([array<string|int, string>|string|null $attributeNames = null ][, bool $clearErrors = true ]) : bool

This method executes the validation rules applicable to the current [[scenario]]. The following criteria are used to determine whether a rule is currently applicable:

  • the rule must be associated with the attributes relevant to the current scenario;
  • the rules must be effective for the current scenario.

This method will call [[beforeValidate()]] and [[afterValidate()]] before and after the actual validation, respectively. If [[beforeValidate()]] returns false, the validation will be cancelled and [[afterValidate()]] will not be called.

Errors found during the validation can be retrieved via [[getErrors()]], [[getFirstErrors()]] and [[getFirstError()]].

Parameters
$attributeNames : array<string|int, string>|string|null = null

attribute name or list of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.

$clearErrors : bool = true

whether to call [[clearErrors()]] before performing validation

Tags
throws
InvalidArgumentException

if the current scenario is unknown.

Return values
bool

whether the validation is successful without any error.

validateMultiple()

Validates multiple models.

public static validateMultiple(array<string|int, mixed> $models[, array<string|int, mixed>|null $attributeNames = null ]) : bool

This method will validate every model. The models being validated may be of the same or different types.

Parameters
$models : array<string|int, mixed>

the models to be validated

$attributeNames : array<string|int, mixed>|null = null

list of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.

Return values
bool

whether all models are valid. False will be returned if one or multiple models have validation error.

createRelationQuery()

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

protected createRelationQuery(string $class, array<string|int, mixed> $link, bool $multiple) : ActiveQueryInterface
Parameters
$class : string

the class name of the related record.

$link : array<string|int, mixed>

the primary-foreign key constraint.

$multiple : bool

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

Tags
since
2.0.12
see
hasOne()
see
hasMany()
Return values
ActiveQueryInterface

the relational query object.

deleteInternal()

Deletes an ActiveRecord without considering transaction.

protected deleteInternal() : int|false
Tags
throws
StaleObjectException
Return values
int|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.

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".

protected extractFieldsFor(array<string|int, mixed> $fields, string $rootField) : array<string|int, mixed>
Parameters
$fields : array<string|int, mixed>

The fields requested for extraction

$rootField : string

The root field for which we want to extract the nested fields

Tags
since
2.0.14
Return values
array<string|int, mixed>

nested fields extracted for the given field

extractRootFields()

Extracts the root field names from nested fields.

protected extractRootFields(array<string|int, mixed> $fields) : array<string|int, mixed>

Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "item".

Parameters
$fields : array<string|int, mixed>

The fields requested for extraction

Tags
since
2.0.14
Return values
array<string|int, mixed>

root fields extracted from the given nested fields

insertInternal()

Inserts an ActiveRecord into DB without considering transaction.

protected insertInternal([array<string|int, mixed>|null $attributes = null ]) : bool
Parameters
$attributes : array<string|int, mixed>|null = null

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

Return values
bool

whether the record is inserted successfully.

refreshInternal()

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

protected refreshInternal(BaseActiveRecord $record) : bool
Parameters
$record : BaseActiveRecord

the record to take attributes from.

Tags
see
refresh()
since
2.0.13
Return values
bool

whether refresh was successful.

resolveFields()

Determines which fields can be returned by [[toArray()]].

protected resolveFields(array<string|int, mixed> $fields, array<string|int, mixed> $expand) : array<string|int, mixed>

This method will first extract the root fields from the given fields. Then it will check the requested root fields against those declared in [[fields()]] and [[extraFields()]] to determine which fields can be returned.

Parameters
$fields : array<string|int, mixed>

the fields being requested for exporting

$expand : array<string|int, mixed>

the additional fields being requested for exporting

Return values
array<string|int, mixed>

the list of fields to be exported. The array keys are the field names, and the array values are the corresponding object property names or PHP callables returning the field values.

updateInternal()

protected updateInternal([array<string|int, mixed>|null $attributes = null ]) : int|false
Parameters
$attributes : array<string|int, mixed>|null = null

attributes to update

Tags
see
update()
throws
StaleObjectException
Return values
int|false

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

attachBehaviorInternal()

Attaches a behavior to this component.

private attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
$name : string|int

the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.

$behavior : string|array<string|int, mixed>|Behavior

the behavior to be attached

Return values
Behavior

the attached behavior.

columnValueCanBeNormalized()

Check when the column value can be normalized to correct format, e.g. string formatted value '123' should be converted to integer value 123

private columnValueCanBeNormalized(ColumnSchema|null $column, mixed $value) : bool
Parameters
$column : ColumnSchema|null
$value : mixed
Return values
bool

isValueDifferent()

private isValueDifferent(mixed $newValue, mixed $oldValue) : bool
Parameters
$newValue : mixed
$oldValue : mixed
Tags
since
2.0.48
Return values
bool

resetDependentRelations()

Resets dependent related models checking if their links contain specific attribute.

private resetDependentRelations(string $attribute) : mixed
Parameters
$attribute : string

The changed attribute name.

setRelationDependencies()

Sets relation dependencies for a property

private setRelationDependencies(string $name, ActiveQueryInterface $relation[, string|null $viaRelationName = null ]) : mixed
Parameters
$name : string

property name

$relation : ActiveQueryInterface

relation instance

$viaRelationName : string|null = null

intermediate relation


        
On this page

Search results