【发布时间】: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_id 和 slug 已保存。但是当我检查数据库时,hashed_id 和 slug 都是 NULL。仅保存item_id、user_id 和price。我做错了什么,我该如何解决?
【问题讨论】:
-
你考虑过使用观察者吗?
标签: php laravel eloquent laravel-api