首页 > 解决方案 > Laravel 多态类型未正确存储

问题描述

我正在使用 Backpack 为我的项目创建管理面板。我有一个 SoldProduct 模型(基本上是已出售给客户的实物)、一个 Shoe 模型和一个 Sweatshirt 模型。它们之间存在多态关系,以便为它们中的每一个拥有一个单独的表,避免它们共享的列的重复,也避免将它们存储在一个拥有所有必要信息的大表中的(有点丑陋的)解决方案根据所存储的产品类型,这些字段将保持部分为空。

由于我使用的是 Backpack 的 CRUD,因此我创建了一个自定义存储方法,该方法创建特定类型的产品,然后创建一个链接到特定类型的 SoldProduct 对象(通过填充 productable_type 和 productable_id 字段)。

问题是虽然productable_id正确存储,但在productable_type字段中而不是存储例如"App\Models\Shoe"我不断获取"App\Models\SoldProduct"(父模型的名称),我不知道它从哪里得到它。数据正确地传递给“最终”存储方法,但在存储过程中它被修改为"App\Models\SoldProduct".

关于为什么会发生这种情况的任何线索?谢谢大家。

这是我的代码

public function store(Request $request) {

    $this->crud->setRequest($this->crud->validateRequest()); 
    $productable_type = $request->request->get('productable_type');

    switch ($productable_type) {
        case "Shoe":
            $product = new Shoe;
            $product->imprinted_code = $request->request->get('imprinted_code');
            $product->size = $request->request->get('shoe_size');
            $product->sole = $request->request->get('sole');

            $product->save();

            $product_id = $product->id;

            $this->crud->addField(['type' => 'hidden', 'name' => 'productable_id']);
            $this->crud->getRequest()->request->add(['productable_id' => "$product_id"]);
            $this->crud->getRequest()->request->add(['productable_type' => "App\Models\\$productable_type"]); 

            break;
    // repeat for Sweatshirt too
    } 

    $this->removeField('imprinted_code', $request);
    $this->removeField('shoe_size', $request);
    $this->removeField('sole', $request);
    $this->removeField('sweatshirt_size', $request);
    $this->removeField('shirt_size', $request);
    $this->removeField('pants_size', $request); 

    $this->crud->unsetValidation();

    return $this->traitStore();
}

已售产品表

Schema::create('sold_products', function (Blueprint $table) {
       $table->id();
       $table->foreignId('product_model_id')->constrained('product_models');
       $table->foreignId('owner_id')->nullable()->constrained('users')->onUpdate('cascade');
       $table->integer('productable_id')->nullable();
       $table->string('productable_type')->nullable();
       $table->string('note')->nullable();
       $table->timestamps();
});

已售产品

public function productable() {
    return $this->morphTo();
}

鞋子

public function product() {
    return $this->morphOne('App\Models\SoldProduct', 'productable');
}

运动衫

public function product() {
    return $this->morphOne('App\Models\SoldProduct', 'productable');
}

标签: laravelpolymorphismlaravel-8laravel-backpack

解决方案


推荐阅读