update() public method
Saves the changes to this active record into the associated database table.
This method performs the following steps in order:
- call beforeValidate() when
$runValidation
istrue
. If beforeValidate() returnsfalse
, the rest of the steps will be skipped; - call afterValidate() when
$runValidation
istrue
. If validation failed, the rest of the steps will be skipped; - call beforeSave(). If beforeSave() returns
false
, the rest of the steps will be skipped; - save the record into database. If this fails, it will skip the rest of the steps;
- call afterSave();
In the above step 1, 2, 3 and 5, events EVENT_BEFORE_VALIDATE, EVENT_AFTER_VALIDATE, EVENT_BEFORE_UPDATE, and EVENT_AFTER_UPDATE will be raised by the corresponding methods.
Only the changed attribute values will be saved into database.
For example, to update a customer record:
$customer = Customer::findOne($id); $customer->name = $name; $customer->email = $email; $customer->update();
Note that it is possible the update does not affect any row in the table. In this case, this method will return 0. For this reason, you should use the following code to check if update() is successful or not:
if ($customer->update() !== false) { // update successful } else { // update failed }
public integer|false update ( $runValidation = true, $attributeNames = null ) | ||
---|---|---|
$runValidation | boolean |
Whether to perform validation (calling validate()) before saving the record. Defaults to |
$attributeNames | array |
List of attribute names that need to be saved. Defaults to null, meaning all attributes that are loaded from DB will be saved. |
return | integer|false |
The number of rows affected, or |
throws | yii\db\StaleObjectException |
if optimistic locking is enabled and the data being updated is outdated. |
throws | yii\db\Exception |
in case update failed. |
Please login to continue.