Yii2如何在afterSave

时间:2018-05-17 01:12:42

标签: php activerecord yii2 after-save

我有一个模型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()。

还有其他办法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该使用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']);
     return true;
}