【问题标题】:function static::created does not save properly Laravel函数 static::created 无法正确保存 Laravel
【发布时间】:2020-03-12 11:06:20
【问题描述】:

所以我有 2 个表:Item 和 Product。一个项目hasMany 产品和一个产品belongsTo 一个项目。

产品迁移:

Schema::create('products', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('hashed_id')->nullable()->unique();
    $table->bigInteger('item_id')->unsigned();
    $table->bigInteger('user_id')->unsigned();
    $table->integer('state')->default(1);
    $table->decimal('price');
    $table->string('slug')->nullable()->unique();
    $table->timestamps();

    $table->foreign('item_id')->references('id')->on('items')->onDelete('cascade');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

对于 hashed_id,我使用以下包:https://packagist.org/packages/hashids/hashids 创建一个散列 id 以显示在 url 中。

产品.php

public static function boot()
{
    parent::boot();

    static::created(function ($product) {
        $productId = $product->id;
        $hashids = new Hashids("", 10, 'abcdefghijklmnopqrstuvwxyz1234567890');
        $hashedId = $hashids->encode($productId++);

        $slug = Str::slug($product->item->slug . '-' . $hashedId);

        $product->hashed_id = $hashedId;
        $product->slug = $slug;
    });

}

ProductsController.php

public function createSelfProduct(Request $request)
{
    $product = auth()->user()->products()->create([
        'item_id' => $request->item_id,
        'user_id' => auth()->user()->id,
        'price' => $request->price,
    ]);

    // create the product and show seller info
    return new ProductResource($product->load('user'));
}

我要做的是,当用户创建新产品时,它应该从项目模型中获取slug,将$hashedId 放在它后面并将其保存到数据库中。现在,当我通过 Postman 发出帖子请求时,我得到了想要的结果,因为 hashed_idslug 已保存。但是当我检查数据库时,hashed_idslug 都是 NULL。仅保存item_iduser_idprice。我做错了什么,我该如何解决?

【问题讨论】:

  • 你考虑过使用观察者吗?

标签: php laravel eloquent laravel-api


【解决方案1】:

Laravel 有一种使用观察者处理这个问题的便捷方式

https://laravel.com/docs/5.8/eloquent#observers

php artisan make:observer ProductObserver

然后在 Observers/ProductObserver.php 中

public function created(Product $product) {

    $product = ''; // whatver you need to do here. $product is an instance of Product model

    // Dont forget to save your model after modifying
    $product->save();

}

【讨论】:

  • 虽然这不是解决我问题的答案,但我会更多地研究观察者模式,非常感谢。
【解决方案2】:

created 事件表示模型已经创建。这不是在保存之前,而是在保存之后。如果您此时更改任何内容,则需要再次保存记录。

简单地说:您忘记在模型实例上调用 save 以在更改后保存更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2020-01-30
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 2020-03-27
    相关资源
    最近更新 更多