1

我是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,
            ]);
}
4

3 回答 3

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

public function sendMail($event) {

}
于 2018-03-07T12:47:44.617 回答
1

您可以在损害模型中创建一个属性$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;

    // ...

}
于 2016-09-01T07:24:23.863 回答
1

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

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

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

于 2016-09-01T07:24:56.807 回答