PHP Class yii\db\ActiveRecord
Active Record implements the
Active Record design pattern.
The premise behind Active Record is that an individual
ActiveRecord object is associated with a specific
row in a database table. The object's attributes are mapped to the columns of the corresponding table.
Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
As an example, say that the
Customer ActiveRecord class is associated with the
customer table.
This would mean that the class's
name attribute is automatically mapped to the
name column in
customer table.
Thanks to Active Record, assuming the variable
$customer is an object of type
Customer, to get the value of
the
name column for the table row, you can use the expression
$customer->name.
In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
But Active Record provides much more functionality than this.
To declare an ActiveRecord class you need to extend
ActiveRecord and
implement the
tableName method:
php
The tableName method only has to return the name of the database table associated with the class.
> Tip: You may also use the Gii code generator to generate ActiveRecord classes from your
> database tables.
Class instances are obtained in one of two ways:
* Using the new operator to create a new, empty object
* Using a method to fetch an existing record (or records) from the database
Below is an example showing some typical usage of ActiveRecord:
php
$user = new User();
$user->name = 'Qiang';
$user->save(); // a new row is inserted into user table
the following will retrieve the user 'CeBe' from the database
$user = User::find()->where(['name' => 'CeBe'])->one();
this will get related records from orders table when relation is defined
$orders = $user->orders;
For more details and usage information on ActiveRecord, see the guide article on ActiveRecord.
Exibir arquivo
Open project: yiisoft/yii2
Class Usage Examples
Public Methods
Method |
Description |
|
attributes ( ) : array |
Returns the list of all attribute names of the model. |
|
delete ( ) : integer | false |
Deletes the table row corresponding to this active record. |
|
deleteAll ( string | array $condition = '', array $params = [] ) : integer |
Deletes rows in the table using the provided conditions. |
|
equals ( ActiveRecord $record ) : boolean |
Returns a value indicating whether the given active record is the same as the current one. |
|
find ( ) : ActiveQuery |
|
|
findBySql ( string $sql, array $params = [] ) : ActiveQuery |
Creates an ActiveQuery instance with a given SQL statement. |
|
getDb ( ) : Connection |
Returns the database connection used by this AR class. |
|
getTableSchema ( ) : yii\db\TableSchema |
Returns the schema information of the DB table associated with this AR class. |
|
insert ( boolean $runValidation = true, array $attributes = null ) : boolean |
Inserts a row into the associated database table using the attribute values of this record. |
|
isTransactional ( integer $operation ) : boolean |
Returns a value indicating whether the specified operation is transactional in the current [[scenario]]. |
|
loadDefaultValues ( boolean $skipIfSet = true ) |
Loads default values from database table schema |
|
populateRecord ( $record, $row ) |
|
|
primaryKey ( ) : string[] |
Returns the primary key name(s) for this AR class. |
|
tableName ( ) : string |
Declares the name of the database table associated with this AR class. |
|
transactions ( ) : array |
Declares which DB operations should be performed within a transaction in different scenarios. |
|
update ( boolean $runValidation = true, array $attributeNames = null ) : integer | false |
Saves the changes to this active record into the associated database table. |
|
updateAll ( array $attributes, string | array $condition = '', array $params = [] ) : integer |
Updates the whole table using the provided attribute values and conditions. |
|
updateAllCounters ( array $counters, string | array $condition = '', array $params = [] ) : integer |
Updates the whole table using the provided counter changes and conditions. |
|
Protected Methods
Method |
Description |
|
deleteInternal ( ) : integer | false |
Deletes an ActiveRecord without considering transaction. |
|
findByCondition ( mixed $condition ) : yii\db\ActiveQueryInterface |
Finds ActiveRecord instance(s) by the given condition. |
|
insertInternal ( array $attributes = null ) : boolean |
Inserts an ActiveRecord into DB without considering transaction. |
|
Method Details
attributes()
public method
The default implementation will return all column names of the table associated with this AR class.
This method performs the following steps in order:
1. call [[beforeDelete()]]. If the method returns false, it will skip the
rest of the steps;
2. delete the record from the database;
3. call [[afterDelete()]].
In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
will be raised by the corresponding methods.
public delete ( ) : integer | false |
return |
integer | false |
the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
deleteAll()
public static method
WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
For example, to delete all customers whose status is 3:
php
Customer::deleteAll('status = 3');
public static deleteAll ( string | array $condition = '', array $params = [] ) : integer |
$condition |
string | array |
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 |
the parameters (name => value) to be bound to the query. |
return |
integer |
the number of rows deleted |
deleteInternal()
protected method
Deletes an ActiveRecord without considering transaction.
protected deleteInternal ( ) : integer | false |
return |
integer | false |
the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
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.
public equals ( ActiveRecord $record ) : boolean |
$record |
ActiveRecord |
record to compare to |
return |
boolean |
whether the two active records refer to the same row in the same database table. |
find()
public static method
public static find ( ) : ActiveQuery |
return |
ActiveQuery |
the newly created [[ActiveQuery]] instance. |
findByCondition()
protected static method
This method is internally called by [[findOne()]] and [[findAll()]].
protected static findByCondition ( mixed $condition ) : yii\db\ActiveQueryInterface |
$condition |
mixed |
please refer to [[findOne()]] for the explanation of this parameter |
return |
yii\db\ActiveQueryInterface |
the newly created [[ActiveQueryInterface|ActiveQuery]] instance. |
findBySql()
public static method
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:
php
$customers = Customer::findBySql('SELECT * FROM customer')->all();
public static findBySql ( string $sql, array $params = [] ) : ActiveQuery |
$sql |
string |
the SQL statement to be executed |
$params |
array |
parameters to be bound to the SQL statement during execution. |
return |
ActiveQuery |
the newly created [[ActiveQuery]] instance |
getDb()
public static method
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.
public static getDb ( ) : Connection |
return |
Connection |
the database connection used by this AR class. |
getTableSchema()
public static method
Returns the schema information of the DB table associated with this AR class.
public static getTableSchema ( ) : yii\db\TableSchema |
return |
yii\db\TableSchema |
the schema information of the DB table associated with this AR class. |
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:
php
$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
public insert ( boolean $runValidation = true, array $attributes = null ) : boolean |
$runValidation |
boolean |
whether to perform validation (calling [[validate()]])
before saving the record. Defaults to `true`. If the validation fails, the record
will not be saved to the database and this method will return `false`. |
$attributes |
array |
list of attributes that need to be saved. Defaults to `null`,
meaning all attributes that are loaded from DB will be saved. |
return |
boolean |
whether the attributes are valid and the record is inserted successfully. |
insertInternal()
protected method
Inserts an ActiveRecord into DB without considering transaction.
protected insertInternal ( array $attributes = null ) : boolean |
$attributes |
array |
list of attributes that need to be saved. Defaults to `null`,
meaning all attributes that are loaded from DB will be saved. |
return |
boolean |
whether the record is inserted successfully. |
isTransactional()
public method
Returns a value indicating whether the specified operation is transactional in the current [[scenario]].
public isTransactional ( integer $operation ) : boolean |
$operation |
integer |
the operation to check. Possible values are [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]]. |
return |
boolean |
whether the specified operation is transactional in the current [[scenario]]. |
loadDefaultValues()
public method
You may call this method to load default values after creating a new instance:
php
class Customer extends \yii\db\ActiveRecord
$customer = new Customer();
$customer->loadDefaultValues();
public loadDefaultValues ( boolean $skipIfSet = true ) |
$skipIfSet |
boolean |
whether existing value should be preserved.
This will only set defaults for attributes that are `null`. |
populateRecord()
public static method
primaryKey()
public static method
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.
public static primaryKey ( ) : string[] |
return |
string[] |
the primary keys of the associated database table. |
tableName()
public static method
By default this method returns the class name as the table name by calling [[Inflector::camel2id()]]
with prefix [[Connection::tablePrefix]]. For example if [[Connection::tablePrefix]] is tbl_,
Customer becomes tbl_customer, and OrderItem becomes tbl_order_item. You may override this method
if the table is not named after this convention.
transactions()
public method
The supported DB operations are: [[OP_INSERT]], [[OP_UPDATE]] and [[OP_DELETE]],
which correspond to the
ActiveRecord::insert,
ActiveRecord::update and
ActiveRecord::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,
php
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 (
ActiveRecord::insert)
should be done in a transaction; and in the "api" scenario, all the operations should be done
in a transaction.
public transactions ( ) : array |
return |
array |
the declarations of transactional operations. The array keys are scenarios names,
and the array values are the corresponding transaction operations. |
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:
php
$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:
php
if ($customer->update() !== false) {
update successful
} else {
update failed
}
public update ( boolean $runValidation = true, array $attributeNames = null ) : integer | false |
$runValidation |
boolean |
whether to perform validation (calling [[validate()]])
before saving the record. Defaults to `true`. If the validation fails, the record
will not be saved to the database and this method will return `false`. |
$attributeNames |
array |
list of attributes that need to be saved. Defaults to `null`,
meaning all attributes that are loaded from DB will be saved. |
return |
integer | false |
the number of rows affected, or false if validation fails
or [[beforeSave()]] stops the updating process. |
updateAll()
public static method
For example, to change the status to be 1 for all customers whose status is 2:
php
Customer::updateAll(['status' => 1], 'status = 2');
public static updateAll ( array $attributes, string | array $condition = '', array $params = [] ) : integer |
$attributes |
array |
attribute values (name-value pairs) to be saved into the table |
$condition |
string | array |
the conditions that will be put in the WHERE part of the UPDATE SQL.
Please refer to [[Query::where()]] on how to specify this parameter. |
$params |
array |
the parameters (name => value) to be bound to the query. |
return |
integer |
the number of rows updated |
updateAllCounters()
public static method
For example, to increment all customers' age by 1,
php
Customer::updateAllCounters(['age' => 1]);
public static updateAllCounters ( array $counters, string | array $condition = '', array $params = [] ) : integer |
$counters |
array |
the counters to be updated (attribute name => increment value).
Use negative values if you want to decrement the counters. |
$condition |
string | array |
the conditions that will be put in the WHERE part of the UPDATE SQL.
Please refer to [[Query::where()]] on how to specify this parameter. |
$params |
array |
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 |
integer |
the number of rows updated |