laravel - 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');
}
解决方案
推荐阅读
- sql - Postgres 更新导致错误“无法确定参数 $3 的数据类型”
- python - ValueError:将字典转换为数据框时,数组的长度必须相同
- c# - 使用 C# 在 XML 文件中的 Xelement 之前添加用于格式化的空间
- windows - 无法在 Windows 10 中解锁 Windows 2016 virtualBox 的睡眠屏幕
- azure - 尝试在 Azure 服务器上创建 sendgrid 帐户时出现问题
- java - 如何编写有效的正则表达式组?
- jquery - jQuery Datatables - 如何检查具有给定 id 的行是否在当前页面上
- kubernetes - 负载分布:所有 HTTP 请求都被重定向到 k8 集群中的单个 pod
- java - 如何让浮动操作按钮在每次点击时旋转
- .net - Eureka 仅显示 1 个 .NET 服务实例