// Define a custom afterSave method in the model class User extends yii\db\ActiveRecord { public function afterSave($insert, $changedAttributes) { // If a new user was created, send a welcome email if ($insert) { $email = new \yii\mail\Message(); $email->setTo($this->email) ->setSubject('Welcome to our site!') ->setHtmlBody('Thanks for signing up. Enjoy our services!'); Yii::$app->mailer->send($email); } parent::afterSave($insert, $changedAttributes); } }
// Define a custom afterSave method in the model class Order extends yii\db\ActiveRecord { public function afterSave($insert, $changedAttributes) { // If the order status was changed to "shipped", update the product inventory if (!$insert && $this->status === 'shipped') { $this->product->decrementQuantity($this->quantity); } parent::afterSave($insert, $changedAttributes); } // Define a relation to the Product model public function getProduct() { return $this->hasOne(Product::class, ['id' => 'product_id']); } } // Define a decrementQuantity method in the Product model class Product extends yii\db\ActiveRecord { public function decrementQuantity($amount) { $this->quantity -= $amount; $this->save(false, ['quantity']); } }In this example, we define an afterSave method in the Order model that updates the product inventory when the order status is changed to "shipped". We achieve this by defining a relation to the Product model and calling a custom method on the product instance. The method decrements the product quantity and saves the changes to the database. Package library: Yii2 framework.