如何将参数传递给 yii2 中的 afterSave() 方法?

How to passing parameter to afterSave() Method in yii2?

我是 yii2 的新手。我想在插入新记录后编写 afterSave() 方法。我的场景是:当用户添加损坏时,必须向他发送电子邮件。 用户添加损坏时,不输入序列号。我应该读他的名字和串行损坏,但我不知道如何将串行从控制器传递到模型。

伤害模型:

public function getUser()
{
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

 public function afterSave($insert, $changedAttributes)
{
    parent::afterSave($insert, $changedAttributes);
    $name = $this->user->name;
    $serial = ?
    $to = $this->user->email;
    $subject = 'new damage';
    $body = 'mr'.$name.'your damage with serial number'.$serial.'is registered';
    if ($insert) {

        App::sendMail($to, $subject, $body);
    }
}

伤害控制器:

public function actionAddDamage($serial){

  $model = new Damage();
  $gaurantee = Gaurantee::find()->where(['serial' =>  $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
  if (!$gaurantee)
        throw  new ForbiddenHttpException('You don't access');
  $model->gr_id = $gaurantee->id;
  if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);
        }
  return $this->render('addDamage',
            ['model' => $model,
                'servers' => $servers,
                'gaurantee' => $gaurantee,
            ]);
}

您可以在损坏模型中创建一个 属性 $serial 并将序列值分配给控制器中的 $model->serial 属性。例如:

class Damage extends yii\db\ActiveRecord
{
    public $serial = null;

    public function afterSave($insert, $changeAttributes) {
         // ...
         var_dump($this->serial);
    }
}

并且在控制器中,您可以将 $serial 分配给模型:

public function actionAddDamage($serial) {

    $model = new Damage();
    $model->serial = $serial;

    // ...

}

首先想到的是在伤害模型中添加属性。

//Damage model
public $serial;

然后在你的控制器中你可以为此设置值:

public function actionAddDamage($serial){
      $model = new Damage();
      $gaurantee = Gaurantee::find()->where(['serial' =>       $serial])->andWhere(['user_id' => Yii::$app->user->id])->one();
      if (!$gaurantee)
          throw  new ForbiddenHttpException("you don't access");
      $model->serial = $serial;
      .....

在您的 afterSave() 方法中,您的序列号将是 $this->serial

第二种方法是从保证 table 中获取它,因为你有 $this->gr_id ,但这将生成另外 1 个数据库请求。

public function init(){
        $this->on(self::EVENT_AFTER_INSERT, [$this, 'sendMail']);               
    }

public function sendMail($event) {

}