0

我里面有一个模型 ProductOffer 我使用 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()。

还有其他方法吗?

谢谢!

4

1 回答 1

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']);

}
于 2018-05-17T01:37:15.120 回答