Yii2 如何在 afterSave 中重新保存模态

Yii2 how to resave the modal in afterSave

我里面有一个模型 ProductOffer 我使用 afterSave 生成​​优惠券。

现在状态为null,在aftersave中我想更新它。

public function afterSave($insert, $changedAttributes) {
    if (floatval($this->offer) >= floatval($this->product->threshold_price)) {
        $coupon = false;
        $createCoupon = "";
        $ctr = 1;
        while ($coupon == false) {
            $createCoupon = $this->createCoupon(
                "Offer for " . $this->customer_name . ' #' . $this->id, 
                $this->product->sale_price - $this->offer,
                $this->product_id
            );

            if ($createCoupon || $ctr > 3) {
                $coupon = true;
            }

            $ctr++;
        }

        $this->status = self::STATUS_ACCEPTED_COUPON_GENERATED;
        $this->coupon_code = $createCoupon->code;

        // todo this
        // echo "Accepted automatically then send email to customer as the same time to merchant email";
    } else {
        $this->status = self::STATUS_REJECTED;
    }

    return parent::afterSave($insert, $changedAttributes);
}

所以在afterSave我想更新记录状态并保存优惠券代码。

我不想做的就是这样

public function afterSave($insert, $changedAttributes) {

    // So basically I want to update the status in afterSave
    $this->status = "What ever value rejected or accepted it depends of the outcome of generating coupon";
    $this->coupon = "AddTheCoupon";

    // Save or Update
    $this->save();

    return parent::afterSave($insert, $changedAttributes);
}

但它似乎对我不起作用,如果你要分析它,它似乎会无休止地更新数据,因为每次 save() 都会通过 afterSave()。

还有其他方法吗?

谢谢!

您应该使用 updateAttributes 方法,它会跳过所有事件。

参见参考资料 updateAttributes(['some_field'])

/** After record is saved
  */
public function afterSave($insert, $changedAttributes)
{
     parent::afterSave($insert, $changedAttributes);
     
     $this->some_field = 'new_value';
     $this->updateAttributes(['some_field']);

}