【问题标题】:Laravel 5.6 not saving field in `created` model eventLaravel 5.6 未在“已创建”模型事件中保存字段
【发布时间】:2018-06-19 10:02:30
【问题描述】:

我正在尝试从 created 模型事件中保存一个字段,但由于某种原因,stripe_coupon_id 列从未被保存。 created 事件确实像我通过在其中尝试 dd 所测试的那样运行,它确实触发了该事件,但只是不保存该列。

class DiscountRate extends Model
{
    public $table = "discount_rates";

    public $primaryKey = "id";

    public $timestamps = true;

    public $fillable = [
        'id',
        'name',
        'rate',
        'active',
        'stripe_coupon_id'
    ];



    public static function boot()
        {
            parent::boot();
            self::created(function ($discountRate) {
                $coupon_id = str_slug($discountRate->name);
                $discountRate->stripe_coupon_id = $coupon_id;
            });

        }
}

在我的控制器中,我只是调用了一个服务函数,该函数调用了默认的 Laravel 模型创建函数:

public function store(DiscountRateCreateRequest $request)
    {
        $result = $this->service->create($request->except('_token'));

        if ($result) {
            return redirect(route('discount_rates.edit', ['id' => $result->id]))->with('message', 'Successfully created');
        }

    }

discount_rates表:

【问题讨论】:

  • $discountRate->save() 设置后你试过了吗?

标签: php laravel events orm eloquent


【解决方案1】:

创建模型后会触发created 事件。在这种情况下,您需要在最后调用$discountRate->save() 以更新您刚刚创建的模型。

作为替代方案,您可以改用creating 事件。在这种情况下,您最终不需要调用save(),因为模型尚未保存在您的数据库中。 creating 事件的一个很大区别是,如果您使用默认行为自动递增,模型还没有 id。

您可以在here找到有关活动的更多信息。

【讨论】:

    【解决方案2】:

    您必须在创建之前设置stripe_coupon_id。所以在DiscountRate模型的boot方法中替换static::creating而不是self::created

    【讨论】:

    • 为什么要在创建前设置stripe_coupon_id?这不是必需的属性吗? creatingcreated 都发生在不同的时间。我想使用 created 事件,以便我的代码仅在成功创建记录后运行,而不是在 creating 时运行。
    猜你喜欢
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2016-04-15
    相关资源
    最近更新 更多